使用PowerMock

时间:2016-02-29 17:16:29

标签: junit powermock easymock

我希望使用PowerMock模拟方法调用的输出。我的班级看起来像这样:

    public class TestEasyMock {

    private static TestEasyMock TEST_INSTANCE = new TestEasyMock();

    public static TestEasyMock getInstance() {
        return TEST_INSTANCE;
    }

    private Cache<String, String> first = CacheBuilder.newBuilder().
            maximumSize(8192).expireAfterWrite(30, TimeUnit.MINUTES).build();
    private Set<String> second = new TreeSet<String>();

    public String testMethod (String testParam) {
        return first.getIfPresent(testParam);
   }
}

我运行的测试在testMethod调用中抛出NPE,似乎第一个字段为null。由于testMethod被模拟,我期望实际上没有调用testMethod,而是直接返回指示的内容。我正在进行的测试是:

@RunWith(PowerMockRunner.class)
@PrepareForTest({TestEasyMock.class})
public class EasyMockTest {
    @Test
    public void firstTest (){

    suppress(constructor(TestEasyMock.class));
        TestEasyMock testObject = PowerMock.createStrictPartialMockForAllMethodsExcept(TestEasyMock.class, "testMethod");
        EasyMock.expect(testObject.testMethod("blabla")).andReturn("blaTwice");
        EasyMock.replay(testObject);

        String result = TestUtils.replaceString("replaceable");
        assertEquals("replaceable(blaTwice)", result);

    }
}

为什么会发生这种情况?

感谢。

1 个答案:

答案 0 :(得分:0)

使用PowerMock.createStrictPartialMockForAllMethodsExcept(TestEasyMock.class, "testMethod");时,指定testMethod应进行模拟。请参阅PowerMock API文档中的the description of the method