写单元测试遇到下面的问题
BaseTest 中的producer 已经存在值了再次被赋值导致系统异常
org.springframework.beans.factory.BeanCreationException:
Could not inject field: protected mq.producer.Producer BaseTest.producer; nested exception is java.lang.IllegalStateException: The field protected mq.producer.Producer BaseTest.producer cannot have an existing value
mock赋值
org.springframework.boot.test.mock.mockito.MockitoPostProcessor#inject(java.lang.reflect.Field, java.lang.Object, java.lang.String)
private void inject(Field field, Object target, String beanName) {
try {
field.setAccessible(true);
Assert.state(ReflectionUtils.getField(field, target) == null,
() -> "The field " + field + " cannot have an existing value");
Object bean = this.beanFactory.getBean(beanName, field.getType());
ReflectionUtils.setField(field, target, bean);
}
catch (Throwable ex) {
throw new BeanCreationException("Could not inject field: " + field, ex);
}
}
出现问题的原因是 我的单元测试使用了
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@RunWith(JMockit.class)
两种方式
在idea中执行文件夹的时候
在JUNIT执行中发现 当下面runners 中只有一个类的时候是没有任何问题的,多个runner复用的时候 可能会引发一系列的问题。后续类似奇怪的问题可以参考此方案查询
org.junit.runner.JUnitCore#run(org.junit.runner.Runner)
runner = {IdeaSuite48@2281}
myName = "test"
runners = {Collections$UnmodifiableRandomAccessList@2286} size = 8
0 = {JMockit@2292}
1 = {SpringJUnit4ClassRunner@2293}
2 = {SpringJUnit4ClassRunner@2294}
3 = {SpringJUnit4ClassRunner@2295}
4 = {SpringJUnit4ClassRunner@2296}
5 = {SpringJUnit4ClassRunner@2297}
6 = {SpringJUnit4ClassRunner@2298}
7 = {SpringJUnit4ClassRunner@2299}
childrenLock = {Object@2287}
testClass = {TestClass@2288}
filteredChildren = {Collections$UnmodifiableCollection@2289} size = 8
scheduler = {ParentRunner$1@2290}
依赖包
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>1.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.1.2.RELEASE</version>
<scope>test</scope>
</dependency>
使用下面的注解就也么有问题
@RunWith(MockitoJUnitRunner.Silent.class)
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.21.0</version>
<scope>test</scope>
</dependency>