When I’m writting an Spring Boot command line application and I find this issue. Here is how I solve it.
The issue is, after I add actual logic in the “Application.java” file, which is the entrance of the appliction, running unit tests will always hang. Here is the source code of “Application.java”:
@SpringBootTest @RunWith(SpringRunner.class) publicclassDemoTest { @Test publicvoidtest() { System.out.println("This is a demo."); } }
Note that even if the unit test does nothing meaningful, it will still hang when running. I also find that, if I comment out the “this.demoService.execute()” line, the unit test can run without problem. So I update the “Application.java”:
@Override publicvoidrun(ApplicationArguments args) { logger.info("Starting..."); logger.info("Application started with command-line arguments: {}", Arrays.toString(args.getSourceArgs())); logger.info("NonOptionArgs: {}", args.getNonOptionArgs()); logger.info("OptionNames: {}", args.getOptionNames()); for (String name : args.getOptionNames()) { logger.info("arg-" + name + "=" + args.getOptionValues(name)); } // Check if it's running inside of unit testing. Do the actual work only when it's not. if (!this.isRunningInTest()) { this.demoService.execute(); } logger.info("Done."); }
With this update, this issue is solved. However, I’m not sure the root cause of this issue: does it mean the unit test execution has to start after the “Application.class” returns?