模拟接口方法中的空指针异常 [英] Null Pointer Exception in mocking Interface method
问题描述
我使用 TestNG 进行测试,使用 JMockit 来模拟 mockMethod().这是测试用例:
I'm using TestNG for testing and JMockit for mocking mockMethod(). Here's the test case:
@Test
public void testClass1() {
new MockUp<MyInterface>() {
@Mock
public int myMethod(final MyObject someObject ){
return 0;
}
};
MyObject obj = new MyObject();
Assert.assertEquals(obj.mockMethod(someObject),0);
}
}
我为 assertEquals() 调用的 mockMethod() 看起来像这样:
The mockMethod() I'm calling for assertEquals() looks like this:
public class Class1 {
MyInterface my;
public int mockMethod(final MyObject someObject ){
...... //processing steps
return my.myMethod(someObject);
}
}
测试用例抛出空指针异常.我究竟做错了什么?我是否模拟了 mockMethod() 的实现?我也试过了,没用.
Test case throws a Null pointer exception. What am I doing wrong? Do I mock the implementation of mockMethod()? I tried that too, but it hasn't worked.
推荐答案
JMockit 创建了 MyInterface
的模拟实例,但您的测试从未使用过它.可以通过MockUp#getInstance()
方法获取.那么当然测试也需要将实例传递给被测类.
JMockit created a mock instance of MyInterface
, but your test never used it. It can be obtained through the MockUp#getInstance()
method. Then of course the test also needs to pass the instance to the class under test.
这篇关于模拟接口方法中的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!