【问题标题】:mockito testing verify with 0 callsmockito 测试验证 0 次调用
【发布时间】:2017-04-07 22:19:52
【问题描述】:
    Class MyClass{
    method3(){
      if(condition){
        method1()
      }

      else{

      method2()

      }

    }

     method1(){
     //do woo
      }

     method3(){
        //do foo
      }
 }

我试图测试method3,只有在调用 case 时才调用 else 方法。

   MyClass myClassMock=   mock(MyClass.class);
         myClassMock.method3();
         verify( myClassMock, times(0)).method2();

但这会调用我的method2 并在method2 内抛出空指针。我如何在不调用method2 的情况下测试它,因为我的行为不会调用method2。

【问题讨论】:

标签: unit-testing mockito


【解决方案1】:

如果您不关心从 method2 返回的内容,您也可以模拟该方法:

when(mock.method2(anyString())).thenAnswer("anything");

您可以替换 anyString 并使用以下内容:

when(mock.method2(any(MyClass.class))).thenReturn(anInstanceOfMyClass);

或

verify(mock, never()).method2();

或

when(mock.method2()).thenReturn(instanceOfProperClass);

【讨论】:

  • 它是否带任何参数?使用两种第一种方法中的一种。
  • 谢谢试试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
相关资源
最近更新 更多