cannot have an existing value

6 篇文章 0 订阅
5 篇文章 0 订阅

写单元测试遇到下面的问题
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>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值