Search code examples
javajunit5spring-boot-test

@SpringBootTest for main class giving Postrges Communication Exception


I am trying to test Springboot main class for code coverage with junit5. But i am getting:

org.postgresql.util.PSQLException: Connection to 127.0.0.1:5432 refused.

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
@RunWith(SpringRunner.class)
class AlphaApplicationTest {

    @Test
    void main() {
        assertDoesNotThrow(() -> AlphaApplication.main(new String[] {}));
    }
}

Solution

  • Firstly, you tagged the question with junit5, so I assume you are using Junit5. With v5, you shouldn't use the @RunWith annotation ([source])1

    Secondly, you should not run your main method in the test! The SpringBootTest annotation already starts everything! Please read the documentation on testing Spring Boot Applications. When you generate a new project with start.spring.io, it will provide you with a basic unit test, which starts an application context. It should look just like this:

    // Includes omitted for brevity
    @SpringBootTest
    class AlphaApplicationTest {
    
        @Test
        void contextLoads() {
        }
    }
    

    That's all. The rest is Spring "magic".

    For more, see the Spring Guides on testing, e.g., "Testing the Web Layer"

    Also, for testing you usually don't want to use the "real" database. Spring Boot comes with some auto-configuration to use an H2 In-Memory-Database for testing. All you need to do is include the relevant dependencies in your POM:

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    

    You can also use normal Spring Boot configuration for this, by using an applications.properties only for tests in test/resource/application-test.properties