因为测试方法有很多用户案例,如何收集这些案例?
就像
jest
javascript 单元测试
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注释。它允许您将一组测试分组为一个逻辑组。执行测试包后,将更容易导航和了解哪些测试组通过/失败。如果您的 JUnit 测试用例类中有大量测试,则非常有用。
这是一个示例:
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 是适用于所有类型测试引擎的平台,您可以在多种方法/引擎中进行选择来指定您的测试。沿着您草图的方向行驶的引擎是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)
}
}
}
请参阅此第 3 方测试引擎列表。