首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >spring boot测试无法注入TestRestTemplate和MockMvc

spring boot测试无法注入TestRestTemplate和MockMvc
EN

Stack Overflow用户
提问于 2016-08-30 03:14:25
回答 3查看 47.8K关注 0票数 51

我使用的是spring boot 1.4.0.RELEASE。我正在为我的控制器类编写测试。我得到了以下异常。

代码语言:javascript
复制
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)}

这是我的测试类

代码语言:javascript
复制
public class ServiceControllerITTest extends ApplicationTests {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private MockMvc mvc;

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

ApplicationTests.java

代码语言:javascript
复制
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
//@DirtiesContext
public class ApplicationTests {

    @Autowired
    Environment env;

    @Test
    public void contextLoads() {

    }

}
EN

回答 3

Stack Overflow用户

发布于 2016-08-30 05:07:35

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

代码语言:javascript
复制
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
票数 104
EN

Stack Overflow用户

发布于 2017-02-15 21:20:37

要解决这个问题,请不要使用废弃的TestRestTemplate。

已弃用:

代码语言:javascript
复制
import org.springframework.boot.test.TestRestTemplate;

正确:

代码语言:javascript
复制
import org.springframework.boot.test.web.client.TestRestTemplate;

然后,您可以在您的类中使用@Autowired注释:

代码语言:javascript
复制
@Autowired
private TestRestTemplate restTemplate;

不要使用:

代码语言:javascript
复制
@Autowired
private MockMvc mvc;

两者都不起作用。

票数 6
EN

Stack Overflow用户

发布于 2017-03-24 17:18:41

根据Spring boot documentation的说法:

您还可以在非@WebMvcTest(例如SpringBootTest)中自动配置MockMvc,方法是使用@AutoConfigureMockMvc对其进行注释。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39213531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档