Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 982
Leandro Borges Ferreira Avatar asked Nov 04 '25 20:11

Leandro Borges Ferreira


1 Answers

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=8080")

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");
like image 74
Darshan Mehta Avatar answered Nov 07 '25 10:11

Darshan Mehta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!