当一个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>
如何正确操作?我在哪里犯了错误?
@MockBean
,请改用@Mock
。 而且,不要使用MockitoAnnotations.initMocks(this);
,请改用MockitoAnnotations.initMocks(b);
。 - Urosh T.