我有一个非常简单的 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";
}
}
<小时/>
我想在 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)
它将把应用程序加载到上下文中并保持应用程序运行。
关于java - 如何从 junit 测试调用 SpringBoot 应用程序的 main 方法并防止其停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51644653/