java 如何模拟一个类的方法在同一个类的另一个被测试的方法中被调用?

omvjsjqw  于 2023-03-06  发布在  Java
关注(0)|答案(3)|浏览(213)

例如,有一个类A,它有两个方法methodUnderTest()和display(),其中methodUnderTest调用display方法。当使用mockito编写一个junit时,我如何模拟display()方法?

class A{
public int method methodUnderTest{
   //some code
   display();
}

public int display(){
  //some code
}

}
velaa5lx

velaa5lx1#

如果这是您的类:

public static class A{
        public int methodUnderTest() {
            return display();
        }

        public int display(){
            return 1;
        }
    }

然后使用mockito,你可以这样做:

A a = spy(new A());
        when(a.display()).thenReturn(0);
        System.out.println(a.methodUnderTest()); // will print 0

说明:
当你mock()一个类时,没有底层示例,你调用的所有方法都不做任何事情,除非另外指定,否则返回默认值。
当你在一个示例上执行spy()时,所有的调用都会被记录下来,并转发到实际的示例。这意味着你的类行为将保持完全相同,除非你模拟一个特定的调用。
话虽如此,像您这样的情况通常是一个症状,您需要拆分类,并在separating your concerns上投资一点。

epfja78i

epfja78i2#

您不需要使用mockito。在测试中,当您创建测试对象时,可以通过以下方式创建它

A underTest = new A() {
    @Override
    public int display() {
        return <expected result>
    }
}

通过这种方式,您可以控制display方法返回的值的类型。

0ejtzxu1

0ejtzxu13#

如果你想用mockito,我会选择类似这样的代码:

@Spy
private A a;

@Test
public void test() {    
    
    //define the behaviour
    Mockito.when(a.display()).thenReturn(12);
    
    // call methodUnderTest
    int res = a.methodUnderTest();
    
    // check that you get what you want
    Assert.assertEquals(SOME_VALUE, res);
    
}

如果你不想使用注解,你可以这样初始化a

A a = Mockito.spy(new A());

啊!

相关问题