Spring загрузочный тест не может ввести TestRestTemplate и MockMvc
Я использую 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() {
}
}
Ответы
Ответ 1
TestRestTemplate
настраивается только автоматически, когда @SpringBootTest
настроен с помощью webEnvironment
, что означает, что он запускает веб-контейнер и прослушивает HTTP-запросы. Например:
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
Ответ 2
Чтобы работать с этим, не используйте устаревший TestRestTemplate.
Устаревшие:
import org.springframework.boot.test.TestRestTemplate;
Правильно:
import org.springframework.boot.test.web.client.TestRestTemplate;
Затем вы можете использовать аннотацию @Autowired
в своем классе:
@Autowired
private TestRestTemplate restTemplate;
И не используйте:
@Autowired
private MockMvc mvc;
Оба вместе не работают.
Ответ 3
Согласно Spring загрузочная документация:
Вы также можете автоконфигурировать MockMvc
в @WebMvcTest
(например, SpringBootTest
), аннотируя его с помощью @AutoConfigureMockMvc
.