注释测试类的假设下
当一个人进入第二个豆子时如何模拟2豆?
public class A {
...
}
public class B {
private A a;
}
我尝试了:
@MockBean
private A a;
@InjectMocks
private B b;
@Before
public void executedBeforeEach() {
MockitoAnnotations.initMocks(this);
}
但有例外:
org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'B'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However, I failed because: the type 'B' is an interface.
春季版:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/>
</parent>
测试依赖性:
<dependencies>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
如何做正确的?我在哪里犯了一个错误?
您只需要自动b。通过使用注释@MockBean
,您告诉测试弹簧上下文将实际A的实际bean替换为模拟的类型A的实际bean,这将自动将其注入到任何地方在包含(即在您的b bean中)。
@MockBean
private A a;
@Autowire
private B b;
这是在您使用@SpringBootTest