Mockito JUnit 中的 When 子句在调用测试类的方法时不起作用

问题描述

我正在尝试存根测试类的方法。它不起作用。

喜欢在课下测试

enter code here
    Class to test:
    public Class A{
        public String method1(){
          C c=new C();
          int num=c.methodC();
          B b=new B();
          String str=method2(b);
          return str;
        }
   public String method2(B b){
         
          String str=method2(b);
          return str;
        }
    }


JUnit class:

    @RunWith(JUnitPlatform.class)
      Class ATest {

      @InjectMocks
      A a;
    
      @Mock
      C c;
      @Mock
      A a1;

      @BeforeEach 
      public void initMocks() {
        MockitoAnnotations.initMocks(this);
      }
    
      @Test
      public void testMethod1(){

        Mockito.doReturn(34).when(c).methodC(anyString());
        a1=Mockito.mock(A.class);
        Mockito.doReturn("Added successfully").when(a1).method2(any(B.class));
        assertEquals("Added successfully",a.method1());
      }
    }

当我从 C 类存根 methodC(...) 时,它正在工作。但是 A 类的 method2(...) 不是存根。

请告诉我是什么问题和解决方案。

解决方法

您有 2 个选项可以模拟对象的各个部分。

选项 1:使用 @Spy 而不是 @Mock

@ExtendWith(MockitoExtension.class)
class ATest {

    @Spy
    A a;

    @Test
    public void testMethod1() {
        Mockito.doReturn("Added successfully").when(a).method2(any(B.class));
        assertEquals("Added successfully",a.method1());
    }
}

选项 2:使用模拟并标记实际实现

@ExtendWith(MockitoExtension.class)
class ATest {

    @Mock
    A a;

    @Test
    public void testMethod1() {
        Mockito.doReturn("Added successfully").when(a).method2(any(B.class));
        Mockito.doCallRealMethod().when(a).method1();
        assertEquals("Added successfully",a.method1());
    }
}
,

我通过试错法发现,测试类中的方法不能被模拟。如果我们必须模拟一个方法,要么我们必须将这些方法移动到不同的类,要么不模拟它。这是唯一的解决方案。