Spring Boot测试模拟bean

tsa*_*txt 2 testing spring mockito

当一个变成第二个时如何模拟2个豆子?

public class A {
...
}

public class B {
private A a;
}
Run Code Online (Sandbox Code Playgroud)

我试过了:

@MockBean 
private A a;

@InjectMocks 
private B b;

@Before
public void executedBeforeEach() {
MockitoAnnotations.initMocks(this);
}
Run Code Online (Sandbox Code Playgroud)

但有例外:

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.
Run Code Online (Sandbox Code Playgroud)

春季版:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath/>
</parent>
Run Code Online (Sandbox Code Playgroud)

测试依赖项:

<dependencies>
...
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    </dependency>
 </dependencies>
Run Code Online (Sandbox Code Playgroud)

怎么做对?我在哪里犯错了?

Plo*_*log 5

您只需要自动装配B。通过使用批注,@MockBean您将告诉测试Spring上下文用模拟替换实际类型A的实际bean,并且它将自动注入到包含的所有A中(即,在您的B bean中)。

@MockBean 
private A a;

@Autowire
private B b;
Run Code Online (Sandbox Code Playgroud)

这是基于以下假设: @SpringBootTest