为了账号安全,请及时绑定邮箱和手机立即绑定

如何从junit测试调用SpringBoot应用程序的main方法并防止它停止

如何从junit测试调用SpringBoot应用程序的main方法并防止它停止

米脂 2021-06-21 09:13:54
我有一个非常简单的 SpringBoot 应用程序,它在 localhost:8085 处公开了一个休息端点。@SpringBootApplicationpublic class App {    public static void main(String[] args)    {        SpringApplication.run(App.class, args);        System.out.println("The gOaT");    }}@RestControllerpublic 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 gOaT2018-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 hierarchy2018-08-01 21:20:43.470  INFO 4821 --- [       Thread-3] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown如何运行此测试,启动应用程序,然后防止应用程序关闭?
查看完整描述

2 回答

?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

使用以下内容注释您的测试类:

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

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


查看完整回答
反对 回复 2021-06-23
  • 2 回答
  • 0 关注
  • 550 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信