Leandro Borges Ferreira Leandro Borges Ferreira - 4 years ago 441
Java Question

How to run a integration test in Spring with @SpringBootTest

I am trying to learn integration tests with Spring. So I am following this tutorial:

http://www.lucassaldanha.com/unit-and-integration-tests-in-spring-boot/

I am fase a test Class like this:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class GreetingControllerTest {

@Test
public void helloTest(){
TestRestTemplate restTemplate = new TestRestTemplate();
Hello hello = restTemplate.getForObject("http://localhost:8080/hello", Hello.class);

Assert.assertEquals(hello.getMessage(), "ola!");
}
}


But when I mvn install, I get this error:

I/O error on GET request for "http://localhost:8080/hello": Connection refused; nested exception is java.net.ConnectException: Connection refused

So... What am I doing wrong? What I need to do to make my test work?

Note: If I run mvn spring-boot:run the project works fine and I request the end point using any browser.

Answer Source

That's because of the following property in your test class:

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)

As per spring documentation, it binds the application to a random port. So, while sending the request, there's a chance that the app won't be running on port 8080 and hence, you get connection refused error.

If you want to run the app on a particular port, you need to remove webEnvironment property and annotate your class with the following:

@IntegrationTest("server.port=0")

Another approach is to get the port and add it into the url, below is the snippet to get the port:

@Autowired
Environment environment;

String port = environment.getProperty("local.server.port");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download