【问题标题】:NPE in mocked method using PowerMock使用 PowerMock 的模拟方法中的 NPE
【发布时间】: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"); 如何适应?

标签: junit powermock easymock


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    相关资源
    最近更新 更多