首页 > 解决方案 > Junit 流卡在正在运行的嵌入式服务器上

问题描述

我创建了一个小应用程序(RestApi),它基本上包含一个嵌入式灰熊服务器。现在我想测试功能,为此我正在使用 Junit。

在测试类中,我使用@BeforeClass 运行嵌入式服务器,使用@Test 测试功能。在运行测试类时,我可以看到服务器正在启动,但流程被卡住并且没有到达使用 @Test 注释的方法。

测试.java

public class MyTest {

@BeforeClass
public static void init() {
    try {
        MyApplication.grizzlyServerSetup();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


@Test
public void testCreateNewBankAccount() {
     // test some functionality.
}

当我停止服务器时,流程到达测试方法并出现连接被拒绝异常的错误。

注意:使用 PostMan 测试时,应用程序运行良好。

标签: javarestjunit

解决方案


您可能需要在单独的线程中启动 grizzly 服务器,这样它就不会因测试而阻塞您的主线程。

你可以做这样的事情

@BeforeClass
public static void setUp() throws Exception {
    new Thread(() -> {
        try {
            MyApplication.grizzlyServerSetup();
        } catch (IOException e) {
            e.printStackTrace();
        }).run();
}

您可能还需要一种拆卸方法来停止 grizzly 服务器

@AfterClass
public static void tearDown() throws Exception {
    //whatever stuff you need to do to stop it
}

推荐阅读