0

I'm newbie on Kotlin, Mockito. Below code has an error which is caused by engine, an immutable field that is not mocked.

I spent a lot of time trying to solve this problem. I found that a way of mocking works, until I don't understand and don't satisfy that.

  1. move a field to constructor. class Car(val engine: Engine) { ... }
  2. change to mutable field. private var engine = Engine()

Is there any other way?

class Car {

  private val engine = Engine() // here
  var state: String? = null

  fun move() {
    state = engine.state
  }
}

@RunWith(MockitoJUnitRunner::class)
class CarTest {

  @Mock private lateinit var mockedEngine: Engine

  @InjectMocks private val car = Car()

  @Test
  fun test() {
    `when`.(mockedEngine.state).thenReturn("run")
    car.move()
    assertEquals("run", car.state)
  }
}

enter image description here

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
illusionJJ
  • 419
  • 1
  • 7
  • 23
  • Possible duplicate of [How to mock final field? mockito/powermock](https://stackoverflow.com/questions/23629766/how-to-mock-final-field-mockito-powermock) – crgarridos Oct 11 '17 at 12:33
  • Possible duplicate of [How to mock final class with Mockito 2 on Java Module in Android project?](https://stackoverflow.com/questions/43306269/how-to-mock-final-class-with-mockito-2-on-java-module-in-android-project) – zsmb13 Oct 11 '17 at 16:05
  • ^ this question and answer should help you – zsmb13 Oct 11 '17 at 16:06
  • Is final field equally treated final class or final static? I suspect constructor issue for a `car` with injectMocks. – illusionJJ Oct 12 '17 at 12:47

1 Answers1

1

I think you've already answered your question. There is no other good solution. What you suggest as the options (preferably first one) is properly designed class to be testable.

palasjir
  • 208
  • 1
  • 8