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

后端 未结 9 2294
终归单人心
终归单人心 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:41

    Another solution to this issue might be that in case of a test class that is using PowerMockRunner, you might have to add the class that you are mocking to the list, in @PrepareForTest annotation.

    For instance -

    @PrepareForTest({ PcUserService.class })

    0 讨论(0)
  • 2020-12-15 15:45

    You need to create a MOCK of pcUserService first, and then use that mock.

    PcUserService mock = org.mockito.Mockito.mock(PcUserService.class);
    when(mock.read("1")).thenReturn(pcUser);
    
    0 讨论(0)
  • 2020-12-15 15:45

    If you use Kotlin, you should know that methods are final by default. So write open fun instead of fun. Thanks to @djkelly99 for a tip.

    0 讨论(0)
  • 2020-12-15 15:51

    In case others hit this issue....

    It could also be the case that the method you are trying to mock out,pcUserService.read, is declared as a final method. From what I've noticed this appears to cause issues with Mockito.

    0 讨论(0)
  • 2020-12-15 15:51

    In my case it was solved by injecting @MockBean.

    For ex.

    @MockBean
    StateRepository mockStateRepository;
    
    0 讨论(0)
  • 2020-12-15 15:54

    For the help of others who stuck with the same problem;

    The method you are trying to mock , pcUserService.read, is declared as a final method. Static methods appears to cause issues with Mockito.

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