如何从junit测试中调用SpringBoot应用程序的主方法并防止其停止



我有一个非常简单的SpringBoot应用程序,它在localhost:8085上公开了一个rest端点。

@SpringBootApplication
public class App 
{
public static void main(String[] args)
{
SpringApplication.run(App.class, args);
System.out.println("The gOaT");
}
}

@RestController
public class Enpoints {
@RequestMapping("/goat")
public String home() {
return "Goat";
}
}

我想在junit测试中启动我的应用程序。成功做到这一点:

public class SomeTest extends TestCase {
@Test
public void testOne() {
String[] args = new String[0];
App.main(args);
assertTrue(true);
}
}

问题是,一旦单元测试初始化了应用程序,它也会立即关闭它(我认为这是因为单元测试本身终止了(:

2018-08-01 21:20:43.422  INFO 4821 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8085 (http) with context path ''
2018-08-01 21:20:43.428  INFO 4821 --- [           main] com.boot.BootTraining.App                : Started App in 3.168 seconds (JVM running for 3.803)
The gOaT
2018-08-01 21:20:43.468  INFO 4821 --- [       Thread-3] ConfigServletWebServerApplicationContext : Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@56dc1551: startup date [Wed Aug 01 21:20:40 CDT 2018]; root of context hierarchy
2018-08-01 21:20:43.470  INFO 4821 --- [       Thread-3] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

如何运行此测试,启动应用程序,然后阻止应用程序关闭?

用注释测试类

@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

它将把应用程序加载到上下文中,并保持应用程序的运行。

对于测试rest api,您需要mockmvc或类似的框架。用为你的班级添加注释

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

我确实有一个示例项目,可能会对你的起步有所帮助:https://github.com/dhananjay12/test-frameworks-tools/tree/master/test-rest-assured

最新更新