Search code examples
androidkotlinjunitmockitoandroid-junit

How to write junit test for object class in kotlin/android?


Maybe this is very basic question but could not find anything online.

I have created a object class in kotlin contains few methods. I am calling those from ViewModel and I have written junit test case for ViewModel where object class instance is mocked, fine so far.

Now, I want to write junit for my object class separately as well even though from ViewModel verify() calls are working fine.

Some code snippet from my project

object InfoHelper {

    fun method(param: Xyz): Boolean {
        return when(param) {
            Result.OK -> true
            else -> false
        }
    }

}

Solution

  • Unit testing Kotlin object classes:

    The same as testing a Java static method and class. The class under test and it's methods can be tested directly without initialisation.

    Using your class as a loose example..

    object InfoHelper {
        fun method(param: String): Boolean {
            return when(param) {
                "my string" -> true
                else -> false
            }
        }
    }
    

    The test:

    import org.junit.Assert.assertFalse
    import org.junit.Assert.assertTrue
    import org.junit.Test
    
    class InfoHelperTest {
        @Test
        fun `some test returns true`() {
            assertTrue(InfoHelper.method("my string"))
        }
    
        @Test
        fun `some test returns false`() {
            assertFalse(InfoHelper.method("not my string"))
        }
    }