Junit 使用 groovy 预期异常

Junit using groovy expected exception

我有 Spring 启动应用程序。我使用 Junit+Mockito 对其进行单元测试。所有测试用例都是使用 Java 编写的。我最近决定使用 Groovy 编写测试用例,尽管应用程序代码将保留在 Java 中。

我在测试预期异常时遇到了一个奇怪的场景。

场景 1:使用 Junit + Groovy(没有 shouldFail)测试预期异常:

    @Test(expected = NoResultException.class) 
    void testFetchAllNoResultsReturned() throws Exception {
        List<Name> namesLocal = null;
        when(Service.fetchAllNames(id)).thenThrow(
                new NoResultException(""))
        namesLocal = (service.fetchAllNames(id)
        assert(namesLocal==null)
        verify(service, times(1)).fetchAllNames(id)
    }

根据上述测试用例,service.fetchAllNames 调用应抛出 NoResultException。这方面的测试似乎运作良好。但是,之后的assertverify则不是叫。一旦遇到异常,方法就会停止执行。然而,我之前用 Java 编写的测试用例运行得非常好。这个问题是在我切换到 Groovy.

之后才发生的

在做了一些 Google 搜索后,我发现 [=]shouldFail 提供了一个方法 shouldFailGroovyTestCase class 可根据此 link 用于此场景。它确实解决了我的问题。

场景 2:使用 Junit + Groovy(使用 shouldFail )测试预期异常:

    @Test
    void testFetchAllNoResultsReturned() throws Exception {
        List<Name> namesLocal = null;
        when(Service.fetchAllNames(id)).thenThrow(
                new NoResultException(""))
        shouldFail(NoResultException.class) {
            namesLocal = (Service.fetchAllNames(id)
        }
        assert(namesLocal==null)
        verify(Service, times(1)).fetchAllNames(id)
    }

我的疑问是,这是它应该如何工作还是我遗漏了什么。如果这是它应该如何工作的,那么 Groovy 这样做有什么理由吗?我试图在互联网上寻找原因,但找不到很多线索。

However, the assert and verify after that are not called. As soon as the exception is encountered, the method execution stops. However, my earlier test case written in Java worked perfectly well.

给出 java 中的代码:

@Test(expected = NoResultException.class) 
void testFetchAllNoResultsReturned() throws Exception {
    List<Name> namesLocal = null;
    when(Service.fetchAllNames(id)).thenThrow(
            new NoResultException(""))
    namesLocal = (service.fetchAllNames(id)
    ....
}

无论您在 service.fetchAllNames(id) 之后有什么,调用都会抛出异常,测试用例到此结束。由于您定义了预期的异常,因此测试用例将通过。所以这行代码之后的assert和verify在java.

中是绝对不会执行的

我不熟悉 groovy,但从文档来看,您使用 shouldFail 的第二个示例似乎是测试 groovy 中异常的正确方法。 shouldFail 不会终止程序 - 所以它类似于将你的方法调用放在 java

中的 try catch