springboot-运行单元测试-异常与排除

直接跑测试时

package com.fhzheng.demo;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest		//这一行注解会有测试异常
public class SpringbootMysql02ApplicationTests {
	
	@Autowired
	private TestRestTemplate restTemplate;

	@Test
	public void testGetUrl1() {
		//测试getUrl1方法
		String result = restTemplate.getForObject("/hello", String.class);
		assertEquals("Hello Spring Boot", result);
	}
	
	@Test
	public void contextLoads() {
	}

}

出现在异常是:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.test.web.client.TestRestTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1654) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1213) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
	... 29 common frames omitted

解决方式如下:
将头部的注解修改
@RunWith(SpringRunner.class)
@SpringBootTest
改为:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
即:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 

这个代码只是配置,在运行测试时,使用随机端口,当然也可以配置成常用的8080端口

关于Web测试

在运行单元测试时,会启动一个真实的web容器,如果不想启动真实的web容器,则可以设置

WebEnvironment.MOCK

来启动一个模拟的web容器,即

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) 

其实,测试环境下,webEnvironment 属性的默认值就是MOCK,但不知为何不配置就会有问题啊

关于业务组件的测试

一般在测试业务组件时,都在后端,不需要运行Web容器,这时

WebEnvironment.NONE

一般就可以用断言或是直接输出来测试了,当然,自动化测试肯定是用前者
也可用MockBean来模拟业务组件,特别是多组业务调用时,有时需要这样来模拟。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值