spring boot 测试无法注入 TestRestTemplate 和 MockMvc

新手上路,请多包涵

我正在使用弹簧靴 1.4.0.RELEASE 。我正在为我的控制器类编写测试。我得到以下异常。

 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.concur.cognos.authentication.service.ServiceControllerITTest': Unsatisfied dependency expressed through field 'restTemplate': No qualifying bean of type [org.springframework.boot.test.web.client.TestRestTemplate] found for dependency [org.springframework.boot.test.web.client.TestRestTemplate]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.test.web.client.TestRestTemplate] found for dependency [org.springframework.boot.test.web.client.TestRestTemplate]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

这是我的测试课

public class ServiceControllerITTest extends ApplicationTests {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private MockMvc mvc;

    @Test
    public void exampleTest() throws Exception {
         // test
    }
}

ApplicationTests.java

 @RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
//@DirtiesContext
public class ApplicationTests {

    @Autowired
    Environment env;

    @Test
    public void contextLoads() {

    }

}

原文由 brain storm 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
1 个回答

TestRestTemplate 仅在 @SpringBootTest 配置了 webEnvironment 时才会自动配置,这意味着它会启动 Web 容器并侦听 HTTP 请求。例如:

 @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

原文由 Andy Wilkinson 发布,翻译遵循 CC BY-SA 3.0 许可协议