【问题标题】:Each case as separated test in ScalaTest - JUnit ParameterizedTest style每个案例作为 ScalaTest 中的单独测试 - JUnit ParameterizedTest 风格
【发布时间】:2021-03-30 08:42:08
【问题描述】:

这是 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的效果?

【问题讨论】:

    标签: scala scalatest


    【解决方案1】:

    尝试翻转testforall的顺序:

    forAll (correctUsernames) { (name: String) =>
      test(s"should evaluate acceptable usernames as correct $name") {
        UsernameValidator.validate(name) shouldBe true
      }
    }
    

    然后您将运行 3 个测试。

    您编写的测试是声明一个测试,它会在其中进行所有检查。当您翻转订单时,为每个条目创建一个新测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      • 2018-02-08
      • 1970-01-01
      相关资源
      最近更新 更多