抽象父类内部的模拟依赖关系



我有以下一组类:

public abstract class ParentClass {
@Autowired
private SomeService service;
protected Item getItem() {
return service.foo();
}
protected abstract doSomething();
}
@Component
public ChildClass extends ParentClass {
private final SomeOtherService someOtherService;
@Override
protected doSomething() {
Item item = getItem(); //invoking parent class method
.... do some stuff
}
}

尝试测试儿童类:

@RunWith(MockitoJUnitRunner.class)
public class ChildClassTest {
@Mock
private SomeOtherService somerOtherService;
@Mock
private SomerService someService; //dependency at parent class
@InjectMocks
private ChildClass childClass;
public void testDoSomethingMethod() {
Item item = new Item();
when(someService.getItem()).thenReturn(item);
childClass.doSomething();
}
}

问题是,我总是得到一个NullPointerException,因为父依赖项(SomeService(总是为null。

也尝试过:

Mockito.doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
return new Item();
}
}).when(someService).getItem();

和使用间谍,没有任何成功。

谢谢你的提示。

一个选项是使用ReflectionTestUtils类注入mock。在下面的代码中,我已经用JUnit4执行了单元测试。
@RunWith(MockitoJUnitRunner.class)
public class ChildClassTest {
@Mock
private SomeService someService;
@Test
public void test_something() {
ChildClass childClass = new ChildClass();       
ReflectionTestUtils.setField(childClass, "service", someService);

when(someService.foo()).thenReturn("Test Foo");

assertEquals("Child Test Foo", childClass.doSomething());
}

}

最新更新