gpt4 book ai didi

java - 如何使用 Mockito 模拟父抽象类中声明的依赖项?

转载 作者:行者123 更新时间:2023-11-30 05:32:43 31 4
gpt4 key购买 nike

我有两个类,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正在被正确 mock ,但是 servicenull 。有人可以告诉我如何在我的测试类中成功模拟这两个服务(依赖项)吗?

最佳答案

在测试中,类添加此内容并尝试

@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}

关于java - 如何使用 Mockito 模拟父抽象类中声明的依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57218216/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com