我是测试的新手,目前正在测试Spring应用程序中的服务和控制器。
当我开始在服务层中进行集成测试时,我发布了一个注释
@SpringBootTest (webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
总是出现错误:
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest (classes = ...) with your test
然后,作为解决方案,我设置了如下注释:
@SpringBootTest (classes = MyApplication.class)
,一切正常。
但是现在我已经开始测试控制器层,并且我需要一个TestRestTemplate:
@Autowired
private TestRestTemplate restTemplate;
我收到错误消息:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.ftn.controllers.AddressControllerTest': Unsatisfied dependency expressed through field 'restTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.test.web.client.TestRestTemplate' available: expected at least 1 bean which qualifies as an autowire candidate. Dependency annotations: {@ org.springframework.beans.factory.annotation.Autowired (required = true)}
我的测试班:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TicketServiceApplication.class)
@Transactional
@TestPropertySource("classpath:application-test.properties")
public class AddressControllerTest {
@Autowired
private AddressRepository addressRepository;
@Autowired
private TestRestTemplate restTemplate;
private String accessToken;
private HttpHeaders headers = new HttpHeaders();
@Before
public void login() {
ResponseEntity<LoggedInUserDTO> login = restTemplate.postForEntity("/login", new LoginDTO("admin", "admin"), LoggedInUserDTO.class);
accessToken = login.getBody().getToken();
headers.add("Authorization", "Bearer "+accessToken);
}
@Test
public void testGetAllAddresses() {
ResponseEntity<AddressDto[]> responseEntity = restTemplate.getForEntity("/api/address", AddressDto[].class);
AddressDto[] addressesDto = responseEntity.getBody();
AddressDto a1 = addressesDto[1];
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertNotNull(addressesDto);
assertNotEquals(0, addressesDto.length);
assertEquals(2, addressesDto.length);
assertEquals(AddressConst.DB_STATE, a1.getState());
assertEquals(AddressConst.DB_CITY, a1.getCity());
assertEquals(AddressConst.DB_STREET, a1.getStreet());
assertEquals(AddressConst.DB_NUM, a1.getNumber());
}
}
什么是正确的解决方案,什么是正确进行集成测试的正确方法?
为什么在SpringBootTest中使用webEnvironment会让我遇到问题?
编辑:现在,当我删除@RunWith()注释时,TestRestTemlpate为null,并且在我尝试获取响应对象的测试的第一行中出现NullPointerException。
如果有人可以帮助和解释一下,抱歉,但是我是弹簧测试的新手。谢谢!