直接跑测试时
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来模拟业务组件,特别是多组业务调用时,有时需要这样来模拟。