我使用的是spring boot 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() {
}
}
发布于 2016-08-30 05:07:35
只有当@SpringBootTest
配置了webEnvironment
时,才会自动配置TestRestTemplate
,这意味着它会启动web容器并侦听HTTP请求。例如:
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
发布于 2017-02-15 21:20:37
要解决这个问题,请不要使用废弃的TestRestTemplate。
已弃用:
import org.springframework.boot.test.TestRestTemplate;
正确:
import org.springframework.boot.test.web.client.TestRestTemplate;
然后,您可以在您的类中使用@Autowired
注释:
@Autowired
private TestRestTemplate restTemplate;
不要使用:
@Autowired
private MockMvc mvc;
两者都不起作用。
发布于 2017-03-24 17:18:41
根据Spring boot documentation的说法:
您还可以在非@WebMvcTest
(例如SpringBootTest
)中自动配置MockMvc
,方法是使用@AutoConfigureMockMvc
对其进行注释。
https://stackoverflow.com/questions/39213531
复制相似问题