每个案例作为 ScalaTest 中的单独测试 - JUnit ParameterizedTest 样式
Each case as separated test in ScalaTest - JUnit ParameterizedTest style
这是 JUnit 中的参数化测试:
@ParameterizedTest
@ValueSource(strings = {"Username", "User123", "Another username", "Another_username" })
@DisplayName("should evaluate acceptable usernames as correct")
public void shouldEvaluateAcceptableUsernamesAsCorrect(String username) {
assertThat(UsernameValidator.validate(username)).isTrue();
}
之后,在 IntelliJ 的测试结果部分,可以看到哪些参数测试失败了 - 这非常方便。
在 ScalaTest 中也可以编写参数化测试:
class UsernameValidatorTests extends AnyFunSuite with Matchers {
val correctUsernames = Table("Username", "User123", "Another username", "Another_username")
test("should evaluate acceptable usernames as correct") {
forAll (correctUsernames) { (name: String) =>
UsernameValidator.validate(name) shouldBe true
}
}
}
但在这个解决方案中,它只是对所有情况进行一次测试。
是否可以在ScalaTest中实现JUnit的效果?
尝试翻转 test
和 forall
顺序:
forAll (correctUsernames) { (name: String) =>
test(s"should evaluate acceptable usernames as correct $name") {
UsernameValidator.validate(name) shouldBe true
}
}
然后你将进行 3 次测试 运行。
您编写的测试声明了一个测试,其中进行了所有检查。当您翻转顺序时,对于每个条目,您都会创建一个新测试。
这是 JUnit 中的参数化测试:
@ParameterizedTest
@ValueSource(strings = {"Username", "User123", "Another username", "Another_username" })
@DisplayName("should evaluate acceptable usernames as correct")
public void shouldEvaluateAcceptableUsernamesAsCorrect(String username) {
assertThat(UsernameValidator.validate(username)).isTrue();
}
之后,在 IntelliJ 的测试结果部分,可以看到哪些参数测试失败了 - 这非常方便。
在 ScalaTest 中也可以编写参数化测试:
class UsernameValidatorTests extends AnyFunSuite with Matchers {
val correctUsernames = Table("Username", "User123", "Another username", "Another_username")
test("should evaluate acceptable usernames as correct") {
forAll (correctUsernames) { (name: String) =>
UsernameValidator.validate(name) shouldBe true
}
}
}
但在这个解决方案中,它只是对所有情况进行一次测试。
是否可以在ScalaTest中实现JUnit的效果?
尝试翻转 test
和 forall
顺序:
forAll (correctUsernames) { (name: String) =>
test(s"should evaluate acceptable usernames as correct $name") {
UsernameValidator.validate(name) shouldBe true
}
}
然后你将进行 3 次测试 运行。
您编写的测试声明了一个测试,其中进行了所有检查。当您翻转顺序时,对于每个条目,您都会创建一个新测试。