How can I mock methods of @InjectMocks class?

前端 未结 3 1354
慢半拍i
慢半拍i 2021-01-30 03:02

For example I have handler:

@Component
public class MyHandler {

  @AutoWired
  private MyDependency myDependency;

  public int someMethod() {
    ...
    retur         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-30 03:30

    First of all the reason for mocking MyHandler methods can be the following: we already test anotherMethod() and it has complex logic, so why do we need to test it again (like a part of someMethod()) if we can just verify that it's calling?
    We can do it through:

    @RunWith(MockitoJUnitRunner.class}
    class MyHandlerTest {
    
      @Spy  
      @InjectMocks  
      private MyHandler myHandler;  
    
      @Mock  
      private MyDependency myDependency;  
    
      @Test  
      public void testSomeMethod() {  
        doReturn(1).when(myHandler).anotherMethod();  
        assertEquals(myHandler.someMethod() == 1);  
        verify(myHandler, times(1)).anotherMethod();  
      }  
    }  
    

    Note: in case of 'spying' object we need to use doReturn instead of thenReturn(little explanation is here)

提交回复
热议问题