Issue
I have an unit test on Spring Boot:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class CustomerControllerIT {
private RestTemplate restTemplate = new RestTemplate();
@Test
public void findAllCustomers() throws Exception {
ResponseEntity<List<Customer>> responseEntity = restTemplate.exchange(
"http://localhost:8080/Customer", HttpMethod.GET, null,
new ParameterizedTypeReference<List<Customer>>() {
});
List<Customer> list = responseEntity.getBody();
Assert.assertEquals(list.size(), 0);
}
}
If I launch test on started application - tests ok
If I try to launch only IT, there is connection refused error
My application.properties
is same for single start.
For tests and located in resources and testResources.
Application.class is:
@ComponentScan({"mypackage"})
@EntityScan(basePackages = {"mypackage.model"})
@EnableJpaRepositories(basePackages = {"mypackage.persistence"})
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Solution
You must run a test with a running server ,
If you need to start a full running server, you can use random ports:
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
An available port is picked at random each time your test runs
You need this maven dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
Example:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class TestRest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void findAllCustomers() throws Exception {
ResponseEntity<List<Customer>> responseEntity = restTemplate.exchange(
"/Customer", HttpMethod.GET, null,
new ParameterizedTypeReference<List<Customer>>(){});
List<Customer> list = responseEntity.getBody();
Assert.assertEquals(list.size(), 0);
}
}
Please read the documentation for more reference
Answered By - Fernix