I have an application where users have to enter different strings. Depending on the nature of the string in the application, it has to follow some rules, for example if it is a name it must begin with a letter.
I wrote a rule to be sure that a string is valid, in the case of a string that must start with a letter I wrote the following rule:
fun String.isFirstCharALetter(): Boolean = this[0].isLetter()
A function extension checks all the rules that apply to a specific string:
fun String.validateName(): String {
check(this.isFirstCharALetter()) { "The first character of a name can only be a letter" }
//... other checks
return this
}
I use this function extension to instantiate a Name
only if the string is valid (at least it is my intention):
data class Name(val value: String) {
companion object {
operator fun invoke(strg: String) {
Name(value= strg.validate())
}
}
}
I wrote the following unit test:
@Test
fun test_assert_name() {
assertFailsWith<IllegalStateException> { Name("8foo") }
}
Since 8foo does not begin with a letter, I expect that an IllegalStateException
exception is raised when a Name
is instantiated with this string, so the test above must succeed.
But the test fails with the following message:
java.lang.AssertionError: Expected an exception of class java.lang.IllegalStateException to be thrown, but was completed successfully.
Does anyone see where I do an error ?
Aucun commentaire:
Enregistrer un commentaire