bra*_*orm 40 spring-mvc spring-test 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)}
Run Code Online (Sandbox Code Playgroud)
这是我的测试课
public class ServiceControllerITTest extends ApplicationTests {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private MockMvc mvc;
@Test
public void exampleTest() throws Exception {
// test
}
}
Run Code Online (Sandbox Code Playgroud)
ApplicationTests.java
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
//@DirtiesContext
public class ApplicationTests {
@Autowired
Environment env;
@Test
public void contextLoads() {
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*son 77
TestRestTemplate仅@SpringBootTest在配置了a 时自动配置,webEnvironment这意味着它启动Web容器并侦听HTTP请求.例如:
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)
如果您阅读SpringBootTest批注的Java文档,则说明该批注提供了以下功能(此处未列出所有功能,而仅列出了与问题相关的内容。)
因此@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)提供了自动连接TestRestTemplate的功能,因为它启动了一个完全运行的Web服务器(也正如@AndyWilkinson的回答中所述)。
但是,如果您也想在同一TestClass中自动连接MockMvc,则在TestClass上使用@AutoConfigureMockMvc批注。
这是Test类的外观:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class SBTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private MockMvc mvc;
// tests
}
Run Code Online (Sandbox Code Playgroud)
小智 5
为此,请不要使用不推荐使用的TestRestTemplate。
不推荐使用:
import org.springframework.boot.test.TestRestTemplate;
Run Code Online (Sandbox Code Playgroud)
正确:
import org.springframework.boot.test.web.client.TestRestTemplate;
Run Code Online (Sandbox Code Playgroud)
然后,您可以@Autowired在课程中使用注释:
@Autowired
private TestRestTemplate restTemplate;
Run Code Online (Sandbox Code Playgroud)
并且不要使用:
@Autowired
private MockMvc mvc;
Run Code Online (Sandbox Code Playgroud)
两者都不起作用。
| 归档时间: |
|
| 查看次数: |
27193 次 |
| 最近记录: |