Home > other >  Spring Boot unit test executing the main class
Spring Boot unit test executing the main class

Time:03-20

When I running my unit test for spring boot application, I discover a strange behaviour of try to execute my Main class. Is there is a reason behind it or any way to stop this happening.

My Main class

@SpringBootApplication
public class SampleMain  implements CommandLineRunner {
    
    private static final Logger logger = LogManager.getLogger(SampleMain.class);

    public static void main(String[] args) {
        System.out.println("test");
    }

    @Override
    public void run(String... args) throws Exception {
        logger.info("running main..");      
    }

}

Unit Test

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
class SampleTest {

    @Test
    void test() {
        assertTrue(true);
    }

}


And when I'm running the unit test, it also execute my Main class (SampleMain)

INFO 13912 --- [main] org.dec.image.SampleTest : Starting SampleTest using Java 17.0.1 on DESKTOP with PID 13912 (started by boomr in C:\java\git\image-duplicates)

INFO 13912 --- [main] org.dec.image.SampleTest : No active profile set, falling back to 1 default profile: "default"

INFO 13912 --- [main] org.dec.image.SampleTest : Started SampleTest in 0.671 seconds (JVM running for 1.703)

INFO 13912 --- [main] org.dec.image.SampleMain : running main..

What is the reason behind it and anyway to stop it?

Edit : What I point out is the skeleton code, it's actually run the main class each time I run the unit test, which kind of annoying as Main class take quite sometimes to run.

CodePudding user response:

I ran into this myself. Its a counter-intuitive way Spring works. I solved it by putting my test application in a package outside of the package which has the main application.

So, if your main application is my.app.SampleMain, try putting your test class in my.test.SampleTest.

  • Related