Spring Boot测试中如何模拟Bean

5
当一个bean依赖另一个bean时,如何模拟这两个bean?
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.

Spring版本:

<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是一个接口,它不能有依赖。 - Maciej Kowalski
类'B'并不像异常信息所说的那样是一个接口。 此外,请勿使用@MockBean,请改用@Mock。 而且,不要使用MockitoAnnotations.initMocks(this);,请改用MockitoAnnotations.initMocks(b); - Urosh T.
1
我理解你的意思。 - tsarenkotxt
1个回答

10

您只需要自动装配B。通过使用注释@MockBean,您告诉测试Spring上下文将A类型的实际bean替换为模拟对象,并且这将自动注入到包含A的任何地方(即在您的B bean中)。

@MockBean 
private A a;

@Autowire
private B b;

假设您已经使用@SpringBootTest注释了测试类,那么以下内容适用。

如果您在嘲笑B,那么就没有理由去嘲笑A,因为您只是在嘲笑B的行为。 - Plog
如果您模拟了B,那么在B内部调用A的任何方法都不会真正发生,因此这并不重要。 - Plog

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接