猿问

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

我有一个非常简单的 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

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


米脂
浏览 551回答 2
2回答

尚方宝剑之说

使用以下内容注释您的测试类:@RunWith(SpringRunner.class) @SpringBootTest(classes = App.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)它将应用程序加载到上下文中并保持您的应用程序运行。
随时随地看视频慕课网APP

相关分类

Java
我要回答