Each case as separated test in ScalaTest - JUnit ParameterizedTest style

Viewed 202

This is parameterized test in 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();
    }

After that in test results section in IntelliJ it's visible for which parameters test failed - and it's very convenient.

parametrized test result in JUnit

In ScalaTest it is also possible to write parameterized test:

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
    }
  }
}

But in this solution it's only one single test for all cases.

parametrized test result in ScalaTest

Is it possible to achievie effect from JUnit in ScalaTest?

1 Answers

Try to flip the test and forall order:

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

Then you will have 3 tests running.

The test you wrote, was declaring one test, which doing all checks in it. When you flip the order, for each entry, you create a new test.

Related