如何模拟@InjectMocks类的方法? [英] How can I mock methods of @InjectMocks class?

查看:569
本文介绍了如何模拟@InjectMocks类的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有处理程序:

@Component
public class MyHandler {

  @AutoWired
  private MyDependency myDependency;

  public int someMethod() {
    ...
    return anotherMethod();
  }

  public int anotherMethod() {...}
}

要测试它,我想写这样的东西:

to testing it I want to write something like this:

@RunWith(MockitoJUnitRunner.class}
class MyHandlerTest {

  @InjectMocks
  private MyHandler myHandler;

  @Mock
  private MyDependency myDependency;

  @Test
  public void testSomeMethod() {
    when(myHandler.anotherMethod()).thenReturn(1);
    assertEquals(myHandler.someMethod() == 1);
  }
}

但是,每当我尝试模拟它时,它实际上就会调用anotherMethod().我应该如何使用myHandler模拟其方法?

But it actually calls anotherMethod() whenever I try to mock it. What should I do with myHandler to mock its methods?

推荐答案

首先,模拟MyHandler方法的原因可能是:我们已经测试了anotherMethod(),它具有复杂的逻辑,所以为什么需要测试如果我们可以verify正在调用它,是否再次调用它(类似于someMethod()的一部分)?
我们可以通过以下方式做到这一点:

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();  
  }  
}  

注意:对于间谍"对象,我们需要使用doReturn而不是thenReturn(小解释是此处)

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

这篇关于如何模拟@InjectMocks类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆