1

///Here is my class

class State {
    var state: Int = 10
}

open class Car {
    var state:State = State()
    fun changState(data: Int = 1) {
         setState(data)
    }
    fun setState(data: Int = 0) {
        state.state = data
    }
}

/// Here is my Test

 @Test
    fun `test 1`() {

        var mockCar = mockk<Car>()

        every { mockCar.changState(any()) } just runs
        every { mockCar.setState(any()) } just runs

        mockCar.changState(10)

        verify(exactly = 1) { mockCar.changState(any()) }
        verify { mockCar.setState(any()) }
    }

But it fails with this error

################################

java.lang.AssertionError: Verification failed: call 1 of 1: Car(#1).setState(any())) was not called.

Calls to same mock:

  1. Car(#1).changState(10)

############################

1 Answers1

3

You need to remove verify { mockCar.setState(any()) } - there is no way that this will ever be called, because you mocked

every { mockCar.changState(any()) } just runs

This means the stubbed method will do nothing, it just runs, so to speak.

I don't recommend writing tests that only test mocks, because it will lead to a bias that the code is fine when you just use outputs of what you think is correct behavior. Instead, write a separate unit test for Car.

For your use-case a mock is not the intended thing to use, you should be using a spy instead if you mix real method calls with mocked behavior.

thinkgruen
  • 929
  • 10
  • 15
  • The objective of the test is when we call car.changState() then setState() is called, also it sets the cart.state.state How can I do that ? – Gopalkrishna Mudaliar Aug 10 '21 at 22:50
  • I'm not sure I understand the objective. What would `changState`, a Unit function with a single line and no conditions do, other than calling `setState`? It doesn't take mocks for this, because the only other class involved is `State`, which imo also requires no mocking. I would just write a test where you call the method, compare if state changed from the initial 10 to something else. Or think about it the other way: what good is testing mock? As I mentioned before, it just leads to bias, because you define behavior the way you think is right, not testing what is actually happening. – thinkgruen Aug 11 '21 at 05:58
  • https://stackoverflow.com/questions/60148997/mockk-spyk-mock-method-only-once here is another helpful question on that matter imo – thinkgruen Aug 11 '21 at 07:12