Home > other >  How can I remove a redundant double bang (!!) from my Unit tests?
How can I remove a redundant double bang (!!) from my Unit tests?

Time:11-06

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?

CodePudding user response:

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.

CodePudding user response:

What can I improve to remove that redundant null check?

Remove the assert(password != null) since it's redundant.

password!! also asserts nonnullity of password. It does it in a way that tells the compiler that either there's an exception thrown here or password is not null, so any following code can assume nonnullity.

kotlin.assert() depends on a runtime jvm -ea flag and therefore it cannot have a nonnull contract.

!! in test code is perfectly fine and you don't need to do anything to get rid of it.

CodePudding user response:

It isn't redundant. The compiler needs it, because the compiler doesn't know what assert() does. And it definitely doesn't know how to interpret a value passed to it like that. You'd need to either change the language so that assert is built into kotlin, or rewrite it to something uglier like if(password != null). Or live with the !!

  • Related