1

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

}
VVB
  • 7,363
  • 7
  • 49
  • 83
  • Why don't you post the actual method under test and the class being passed to it? You've created your own implementation of Result? What is the problem? – JakeB Jun 16 '22 at 10:17
  • Method definition is not important. What I need is should I create ObjectTest class or just like normal kotlin test class – VVB Jun 16 '22 at 10:23

1 Answers1

2

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"))
    }
}
JakeB
  • 2,043
  • 3
  • 12
  • 19
  • Maybe too basic question to ask but just curious to know why it's not ObjectTest instead of ClassTest? – VVB Jun 19 '22 at 01:44