Search code examples
unit-testingkotlinjunitmockito

How can I test method behaviour on not-existing interface implementation in Kotlin?


Let suppose, I have an interface Animal, it has two implementations: Dog and Cat, and we have some method for this class:

fun Animal.sound() : String {
  if (this is Dog) return "woof"
  if (this is Cat) return "meow"
  return "globglogabgalab"
}

Then, I want to test all cases of this method

How can I do that (with JUnit/Mockito), if I don't have an implementation for default behavior?


Solution

  • You could use kotlins Sealed classes in combination with a when statement, then you wouldn't need the last return statement, because that would statement would be unreachable.

    sealed class Animal
    class Dog : Animal()
    class Cat : Animal()
    

    and the sound method would look like this.

    fun Animal.sound() = when (this) {
      is Cat -> "meow"
      is Dog -> "woof"
    }
    

    Alternatively, without sealed classes you could just create a TestAnimal implementation, which implements Animal in your tests, then instantiate it and run the sound() method.

    class TestAnimal : Animal
    
    @Test
    fun foo() {
      TestAnimal().sound()
    }
    

    or with a anonymous implementation

    @Test
    fun foo() {
      val animal = object : Animal {}
    
      animal.sound()
    }