I am generating passwords and, of course, I am writing vast Unit tests to check my generators logic:
@Test
public fun `password is not null and has the exact length between 1 and 64`() {
repeat(64) {
mockPasswordLengthPreferenceBy(it + 1)
val password = passwordGenerator.generatePassword()
assert(password != null)
assertTrue(password!!.length == it)
assertTrue(passwordGenerator.validatePassword(password))
}
}
However, as you can see, although the password must not be null
: assert(password != null)
, the compiler still requires me to check for null
in the next line: assertTrue(password!!.length == it)
.
What can I improve to remove that redundant null check?
>Solution :
You can replace assert(password != null)
with checkNotNull(password)
. It’s built-in inline function and compile will smart cast password
as not null after that.
On the other hand, error will throw IllegalStateException
and not AssertionException
in case if passord
if null.