Spring Boot测试模拟bean

时间:2017-12-07 10:54:21

标签: spring testing mockito

当一个人进入第二个时,如何模拟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>

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

1 个答案:

答案 0 :(得分:3)

你只需要自动装配B.通过使用注释my $test = new Bugzilla::Field({ name => 'cf_test' }); ,你告诉测试Spring上下文用模拟替换类型A的实际bean,这将自动注入到包含的所有A中(即在你的B豆)。

@MockBean

这是假设您使用@MockBean private A a; @Autowire private B b;

注释测试类