如何漂亮地使用junit 5组测试(收集用户案例)

How to use junit 5 group test(gather user cases) in a beautiful way

因为测试方法有很多用户案例,如何收集这些案例?

喜欢jestjavascript单元测试


describe('test methon', () => {
  test('user case one', () => {
    //test code
  });

  test('user case two', () => {
    //test code
  });

  test('user case three', () => {
    //test code
  }); 

  test(...) 
});

我不知道 JUnit5 中的任何东西看起来像您展示的 javascript 中的测试一样富有表现力和简洁。但是至少要考虑一件事,它可以让您以类似的方式对测试进行分组。

@Nested注解。它允许您将一组测试分组到一个逻辑组中。执行测试包后,将更容易导航和理解哪些测试组 passed/failed。如果您的 JUnit 测试用例中有大量测试,这将非常有用 class。 这是它的外观示例:

public class YourTestCase {
    …

    @Nested
    @DisplayName("Tests for my method")
    class MyMethodUseCases {
        @Test
        void testUseCase1() {
            ...
        }

        @Test
        void testUseCase2() {
            ...
        }

        @Test
        void testUseCase3() {
            ...
        }
    }

如果您的测试组共享一些需要在执行测试之前设置的上下文,那么您还可以考虑使用特殊的 JUnit 运行程序,例如 HierarchicalContextRunner。这不是标准 JUnit 的一部分,而是自定义扩展。

最后,如果您的用例之间的唯一区别是数据输入,那么您可能会考虑使用 @ParametrizedTest 注释。它允许您编写一个测试并使用多个数据输入执行它。

因为 JUnit 5 是 platform for all kind of test engines you can choose among many approaches/engines to specify your tests. An engine that goes in the direction you sketch is Specy。这是文档中的示例:

class StackSpec extends ScalaSpecsy {
  val stack = new scala.collection.mutable.Stack[String]
 
  "An empty stack" >> {
 
    "is empty" >> {
      assertTrue(stack.isEmpty)
    }
    "After a push, the stack is no longer empty" >> {
      stack.push("a push")
      assertFalse(stack.isEmpty)
    }
  }
 
  "When objects have been pushed onto a stack" >> {
    stack.push("pushed first")
    stack.push("pushed last")
 
    "the object pushed last is popped first" >> {
      val poppedFirst = stack.pop()
      assertThat(poppedFirst, is("pushed last"))
    }
    "the object pushed first is popped last" >> {
      stack.pop()
      val poppedLast = stack.pop()
      assertThat(poppedLast, is("pushed first"))
    }
    "After popping all objects, the stack is empty" >> {
      stack.pop()
      stack.pop()
      assertTrue(stack.isEmpty)
    }
  }
}

看到这个list of 3rd party test engines