我正在使用TestRestTemplate运行Spring Boot测试。我的代码具有以下自动装配:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT)
class TestMyService
{
...
@Autowired
private TestRestTemplate temp;
private int port = 8080;
...
我的测试使用temp对象进行基本的POST:
String json = temp..postForObject("http://localhost:"+port,params,String.class);
我的测试可以编译并运行,没有问题,但是当我尝试使用以下命令编译Jar文件时:
mvnw clean package
编译失败,并出现以下错误:
[ERROR] basicLetterService(com.factor3.app.counter.TestMyService) Time elapsed: 0.001 s <<< ERROR!
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.factor3.app.counter.TestMyService': Unsatisfied dependency expressed through field 'temp'; nested exception is 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)}
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)}
请注意,失败是由于Boot无法自动连接已声明并成功编译以运行测试的TestRestTemplate对象。
为什么会这样?我需要做些配置细节吗?