【发布时间】:2016-03-02 06:08:40
【问题描述】:
我希望使用 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,似乎第一个字段为空。由于 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) 确切的堆栈跟踪是什么? 2)
TestUtils.replaceString("replaceable");如何适应?