首页 > 解决方案 > Spring Boot mvnw 无法编译代码成功 test-compiled

问题描述

我正在使用 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 对象。

为什么会出现这种情况?我需要做一些配置细节吗?

标签: javaspringspring-boot

解决方案


推荐阅读