2016-02-29 92 views
0

我正在使用PowerMock模拟方法调用的输出。我的阶级是这样的:使用PowerMock模拟方法中的NPE

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); 
    } 
} 

运行测试,抛出NPE在TestMethod的通话,似乎第一个字段为空。由于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); 

    } 
} 

任何想法为什么会发生这种情况?

谢谢。

+0

** 1)**确切的堆栈跟踪是什么? ** 2)** TestUtils.replaceString(“replaceable”);'如何适合? – Morfic

回答

0

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

相关问题