How to make the non-mocked function run in normal

2019-09-08 05:46发布

问题:

I am new in EasyMock, i have a scenario like this:

I create a mock for FolderUtils.ABC(). However, inside the FolderUtils.class, there are many methods that I will use with the ABC() when i run this unitTest. I only want the ABC() return the mock values, otherwise they will run as their normal behavior. How can I do that?

FolderUtils contantsUnderTest = EasyMock.createMock(FolderUtils.class);   
EasyMock.expect(contantsUnderTest.ABC(EasyMock.notNull(UserKey.class))).andReturn("123").anyTimes();

ReflectionTestUtils.setField(field, "folderUtils", contantsUnderTest);

field.execute();

回答1:

Partial mocks can indeed solve your problem. Here is an example:

FolderUtils contantsUnderTest = createMockBuilder(FolderUtils.class)
    .addMockedMethod("ABC")
    .createMock();
expect(contantsUnderTest.ABC(notNull(UserKey.class))).andReturn("123").anyTimes();

replay(contantsUnderTest);

assertEquals("123", contantsUnderTest.ABC(new UserKey()));
assertEquals("1", contantsUnderTest.ANOTHER_CONSTANT());

verify(contantsUnderTest);

for this implementation:

public class FolderUtils {
    public String ABC(UserKey userKey) {
        return "1";
    }

    public String ANOTHER_CONSTANT() {
        return "1";
    }
}