Mockito Exception - when() requires an argument which has to be a method call on a mock

后端 未结 9 2295
终归单人心
终归单人心 2020-12-15 15:12

I have a very simple test case that is using Mockito and Spring Test framework. When I do

when(pcUserService.read(\"1\")).thenReturn(pcUser);
相关标签:
9条回答
  • 2020-12-15 15:59

    There's another possible reason for such error - sometimes IDE prefers to statically import Mockito.when() from another package:

    import static io.codearte.catchexception.shade.mockito.Mockito.when;
    

    vs

    import static org.mockito.Mockito.when; //should normally use this one
    

    The thing is 'when' from io.codearte package is compliant with org.mockito.Mockito.any() on compilation level, but fails during runtime with that exact same error message.

    0 讨论(0)
  • 2020-12-15 16:03

    I had the same issue, the method that I was trying to mock it was a final method. I removed the modifier and it worked fine.

    0 讨论(0)
  • 2020-12-15 16:04

    Basically You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax. For example: PowerMockito.mockStatic(TestClass.class); when(TestClass.getString()).thenReturn("HelloWorld!"); Note: you have to add @PrepareForTest({ TestClass.class }) to your unit test class.

    0 讨论(0)
提交回复
热议问题