Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading