Explanation:
The error message “bad state: cannot call `when` within a stub response” usually occurs when using a mocking library like Mockito or Mockito-Kotlin in testing scenarios.
This error is encountered when attempting to use the `when` keyword to set up a stub response within the internal execution flow of a previously stubbed method.
To understand this error better, let’s consider an example using Mockito in a Kotlin project:
// Assume we have a class called 'MyClass' with a method 'myMethod'
class MyClass {
fun myMethod(): String {
return "Original Response"
}
}
// As part of the test setup, we stub the 'myMethod' to return a specific response
val myClassMock = mock(MyClass::class.java)
`when`(myClassMock.myMethod()).thenReturn("Mocked Response")
// Now, let's test a scenario where the 'myMethod' internally calls 'when' for further stubbing
val myOtherMock = mock(MyClass::class.java)
`when`(myOtherMock.myMethod()).thenReturn("Another Mocked Response")
In the above example, when trying to set up a stub response for `myOtherMock.myMethod()` using the `when` keyword, the “bad state: cannot call `when` within a stub response” error will be thrown.
Solution:
To resolve the error, you need to separate the stubbing operations. Instead of using `when` inside the internal execution flow, you can stub it beforehand outside the method invocation.
Here’s an updated version of the previous example with the proper separation of stubbing:
val myClassMock = mock(MyClass::class.java)
`when`(myClassMock.myMethod()).thenReturn("Mocked Response")
val myOtherMock = mock(MyClass::class.java)
`when`(myOtherMock.myMethod()).thenReturn("Original Response") // Stubbed response should be set before invocation
By moving the stubbing operations outside the internal execution flow, the error should be resolved.