春季启动测试无法注入TestRestTemplate和MockMvc

spring boot test unable to inject TestRestTemplate and MockMvc

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

1
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)}

这是我的考试课

1
2
3
4
5
6
7
8
9
10
11
12
13
public class ServiceControllerITTest extends ApplicationTests {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private MockMvc mvc;

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

ApplicationTests.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
//@DirtiesContext
public class ApplicationTests {

    @Autowired
    Environment env;

    @Test
    public void contextLoads() {

    }

}

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

1
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)


如果您阅读SpringBootTest批注的Java文档,则说明该批注提供了以下功能(此处未列出所有功能,而仅列出了与问题相关的内容。)

  • 提供对不同的webEnvironment模式的支持,包括启动在定义的或随机端口上侦听的完全运行的Web服务器的功能。
  • 注册TestRestTemplate和/或WebTestClient Bean,以用于正在使用完全运行的Web服务器在定义的或随机端口上侦听的Web测试中。

因此@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)提供了自动连接TestRestTemplate的功能,因为它启动了一个完全运行的Web服务器(也正如@AndyWilkinson的回答中所述)。

但是,如果您也想在同一TestClass中自动连接MockMvc,请使用
TestClass上的@AutoConfigureMockMvc批注。

这是Test类的样子:

1
2
3
4
5
6
7
8
9
10
11
12
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class SBTest {
    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private MockMvc mvc;

   // tests
}

为此,请不要使用不推荐使用的TestRestTemplate。

不推荐使用:

1
import org.springframework.boot.test.TestRestTemplate;

正确:

1
import org.springframework.boot.test.web.client.TestRestTemplate;

然后可以在类中使用@Autowired批注:

1
2
@Autowired
private TestRestTemplate restTemplate;

并且不要使用:

1
2
@Autowired
private MockMvc mvc;

两者都不起作用。


根据Spring启动文档:

您也可以在非@WebMvcTest(例如SpringBootTest)中通过@AutoConfigureMockMvc注释自动配置MockMvc