在模拟对象中调用对象 属性 的方法导致 NullPointerException
Calling method of object property in mocked object results in NullPointerException
我有以下场景:
public class MyObject {
ObjectA a;
public void method(){
a.getObjectB.getSomething();
}
现在,在我的 JUnit 测试中,我正在模拟(使用 mockito)并注入 ObjectA,我的问题是即使在我尝试通过反射注入 ObjectB 之后,getObjectB 仍保持为 null。我有什么办法可以解决这个问题吗?
单元测试如下:
@Mock ObjectA a
@Mock ObjectB b
MyObject c
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
c = new MyObject();
MyObject.setObjectA(a);
ReflectionTestUtils.setField(c, "b", b);
when(stepExecution.getObjectB().getSomething()).thenReturn("Stuff);
}
@Test
public void testSomething()
{
c.myMethod()
}
同时模拟对象 ObjectA 和 ObjectB 并根据需要设置它们的期望值。
when(a.getObjectB()).thenReturn(b);
when(b.getSomething()).thenReturn("Stuff");
我有以下场景:
public class MyObject {
ObjectA a;
public void method(){
a.getObjectB.getSomething();
}
现在,在我的 JUnit 测试中,我正在模拟(使用 mockito)并注入 ObjectA,我的问题是即使在我尝试通过反射注入 ObjectB 之后,getObjectB 仍保持为 null。我有什么办法可以解决这个问题吗?
单元测试如下:
@Mock ObjectA a
@Mock ObjectB b
MyObject c
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
c = new MyObject();
MyObject.setObjectA(a);
ReflectionTestUtils.setField(c, "b", b);
when(stepExecution.getObjectB().getSomething()).thenReturn("Stuff);
}
@Test
public void testSomething()
{
c.myMethod()
}
同时模拟对象 ObjectA 和 ObjectB 并根据需要设置它们的期望值。
when(a.getObjectB()).thenReturn(b);
when(b.getSomething()).thenReturn("Stuff");