【问题标题】:How to mock a method call inside another method如何在另一个方法中模拟方法调用
【发布时间】:2014-06-06 23:18:39
【问题描述】:

这是我的代码:

`public class Service {
   callSomeService(ContextTpye1 c1,Parameter p){
   //do something here
   ContextTpye2 c2 = constructContext(c1,p);      
   if(c2.timeout()){
      c2.audit();
     }
   }
 }`

在单元测试中,初始化Service、Parameter和ContextTpye1。是否可以只模拟 c2.audit()?我想让它在这里什么都不做。谢谢。

【问题讨论】:

标签: java unit-testing mockito


【解决方案1】:

因此,假设constructContext(c1,p) 是public,我解决问题的方法是在测试Service 类时监视Service,允许您模拟constructContext(c1,p) 并返回@ 的模拟987654326@.

public class ServiceTest
{
    private Service service = Mockito.spy(new Service());

    private ContextType2 c2 = Mockito.mock(ContextType2.class);

    @Test
    public void testCallSomeService()
    {
        Mockito.when(service.constructContext(Mockito.eq(ContextType1.class), Mockito.eq(Parameter.class))).thenReturn(c2);
            Mockito.when(c2.timeout()).thenReturn(true);
        Mockito.when(c2.audit()).doNothing();
            service.callSomeService(new ContextType1(), new Parameter());
    }
}

【讨论】:

  • 我不能只做'Mockito.when(c2.timeout()).thenReturn(true);' c2 中有一些计算可以给出这个值。
  • 那有什么意义呢?为什么要在服务测试用例中测试 ContextType2.timeout() ?如果要测试超时方法,请为 ContextType2 类创建一个测试用例。在服务类测试用例中,您应该测试服务类方法,而不是服务类调用的其他类的方法。
猜你喜欢
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多