【发布时间】:2019-12-04 16:35:09
【问题描述】:
我有两个类,Parent 和 Child,并且想使用 Mockito 对 Child 类中的一些方法进行单元测试。
public abstract class Parent {
@Resource Service service;
}
@Service // spring service
public class Child extends Parent {
private AnotherService anotherService;
@Autowired
Child(AnotherService anotherService) {
this.anotherService = anotherService;
}
public boolean someMethod() {
}
}
我的测试类如下所示:
@RunWith(MockitoJUnitRunner.class)
public class ChildTest {
@Mock
Service service;
@Mock
AnotherService anotherService;
@InejctMocks
Child classToTest;
@Test
public void testSomething() {
assertTrue(classToTest.someMethod());
}
}
而我面临的问题是 anotherService 被正确地模拟,但 service 是 null。有人可以告诉我如何在我的测试类中成功模拟这两个服务(依赖项)吗?
【问题讨论】:
-
如何实例化 Child?您如何设置/取消依赖项?
-
这实际上与父/子结构无关。相反,它与您使用字段注入有关,而不是构造函数注入。
-
@MaciejKowalski 这是一个 Spring bean。也编辑了问题。感谢您指出这一点。
-
我对你在测试中的表现更感兴趣。你使用 InjectMocks 吗?
-
@Michael 你能详细说明一下吗?子类中的依赖使用的是构造函数注入,而不是字段注入。