[英]How to invoke the main method of a SpringBoot application from a junit test and keep it from stopping
I have a very simple SpringBoot application that exposes a rest endpoint at localhost:8085. 我有一个非常简单的SpringBoot应用程序,该应用程序在localhost:8085公开了一个其他终结点。
@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";
}
}
I'd like to start my application in a junit test. 我想在junit测试中启动我的应用程序。 This succeeds in doing so:
这样成功完成了:
public class SomeTest extends TestCase {
@Test
public void testOne() {
String[] args = new String[0];
App.main(args);
assertTrue(true);
}
}
The problem is, once the unit test initializes the application, it immediately shuts it down too (I think this is because the unit test itself terminates): 问题是,一旦单元测试初始化了应用程序,它也会立即将其关闭(我认为这是因为单元测试本身终止了):
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
How can I run this test, start the application, and then keep the application from closing? 如何运行此测试,启动应用程序,然后阻止应用程序关闭?
Annotate you test class with: 使用以下注释为测试类添加注释:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
It will load the application into the context and keep your application running. 它将应用程序加载到上下文中并保持您的应用程序运行。
For testing rest apis, you either need mockmvc or a similar sort of framework. 为了测试其余的api,您要么需要嘲笑mvcvc,要么需要类似的框架。 Annotate your class with
注释您的班级
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
I do have a sample project that might be helpful for you to get start up: https://github.com/dhananjay12/test-frameworks-tools/tree/master/test-rest-assured 我有一个示例项目,可能对您入门很有帮助: https : //github.com/dhananjay12/test-frameworks-tools/tree/master/test-rest-assured
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.