The error message “bad state: no method stub was called from within `when()`. was a real method called, or perhaps an extension method?” usually occurs when using the Mockito library for unit testing in Java or Kotlin. This error typically occurs when you’re trying to set up behavior for a method using the `when()` method, but the method being stubbed either doesn’t exist or has not been called correctly.
To provide a detailed explanation, let’s consider an example in Kotlin:
// Suppose we have a class with a method we want to test
class MyClass {
fun myMethod(): String {
return "Hello World!"
}
}
// In our test class, we can use Mockito to mock the behavior of MyClass
class MyTestClass {
@Test
fun testMyMethod() {
val myClassMock = Mockito.mock(MyClass::class.java)
Mockito.`when`(myClassMock.myMethod()).thenReturn("Mocked Message")
// Now, if we call myClassMock.myMethod(), it should return the mocked value
val result = myClassMock.myMethod()
// Assertion to check if the mocked value is returned
assertEquals("Mocked Message", result)
}
}
In the above example, we have a class `MyClass` with a method `myMethod()` which returns a string. In our unit test, we are using Mockito to mock the behavior of `myMethod()` by using the `when(myClassMock.myMethod()).thenReturn(“Mocked Message”)` statement. This statement sets up the behavior that whenever `myMethod()` is called on the mock object `myClassMock`, it should return the string “Mocked Message”.
If we encounter the error “bad state: no method stub was called from within `when()`. was a real method called, or perhaps an extension method?”, it may indicate that the method being stubbed (`myMethod()` in this example) doesn’t exist or has been called incorrectly. Make sure that the method being stubbed is a real method of the class and is spelled correctly.
Read more
- The “gopls” command is not available. run “go install -v golang.org/x/tools/gopls@latest” to install.
- Valueerror: cannot setitem on a categorical with a new category, set the categories first
- Bad state: field does not exist within the documentsnapshotplatform
- ‘str’ object has no attribute ‘map’
- Bad file descriptor flutter