【问题标题】:mockito, spy- not sure how it's done for partial mockingmockito,spy - 不知道它是如何完成部分模拟的
【发布时间】:2013-10-01 22:56:49
【问题描述】:

我有一个类,我想模拟该类的某些方法并测试其他方法。这是我可以证实并断言它有效的唯一方法。

class UnderTest{
   public void methodToTest(){
     methodToCall1()
     methodToCall2()
   }


  public void methodToCall1(){
  }

  public void methodToCall2(){
  }

}

现在,由于我想测试第一个方法,我想创建 UnderTest 的部分模拟,以便我可以验证这两个方法是否被调用。 我如何在 Mockito 中实现这一点?

感谢您的帮助!

【问题讨论】:

    标签: java unit-testing mockito powermock


    【解决方案1】:

    你提到你想做两件事:
    1.Create real partial mocks
    2.Verify method invocations

    但是,由于您的目标是验证 methodToCall1()methodToCall2() 是否被实际调用,您需要做的就是 spy on the real object。这可以通过以下代码块来完成:

        //Spy UnderTest and call methodToTest()
        UnderTest mUnderTest = new UnderTest();
        UnderTest spyUnderTest = Spy(mUnderTest);
        spyUnderTest.methodToTest();
    
        //Verify methodToCall1() and methodToCall2() were invoked
        verify(spyUnderTest).methodToCall1();
        verify(spyUnderTest).methodToCall2();
    

    如果其中一个方法没有被调用,例如methodToCall1,则会抛出异常:

        Exception in thread "main" Wanted but not invoked:
        undertest.methodToCall1();
        ...
    

    【讨论】:

      【解决方案2】:
      package foo;
      
      import static org.mockito.Mockito.verify;
      
      import org.junit.Test;
      import org.junit.runner.RunWith;
      import org.mockito.Spy;
      import org.mockito.runners.MockitoJUnitRunner;
      
      @RunWith(MockitoJUnitRunner.class)
      public class FooTest {
      
          @Spy
          private UnderTest underTest;
      
          @Test
          public void whenMethodToTestExecutedThenMethods1And2AreCalled() {
              // Act
              underTest.methodToTest();
      
              // Assert
              verify(underTest).methodToCall1();
              verify(underTest).methodToCall2();
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-20
        • 2017-10-11
        • 1970-01-01
        • 1970-01-01
        • 2021-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多