如何模拟正在被同一类测试的另一个方法内部调用的类的方法?

时间:2019-06-27 06:09:09

标签: java mockito junit4

例如,有一个带有两个方法methodUnderTest()和display()的类A,其中methodUnderTest调用显示方法。使用Mockito编写junit时,如何模拟display()方法?

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

public int display(){
  //some code
}

}

3 个答案:

答案 0 :(得分:2)

如果这是您的课程:

    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上投入一些资金。

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:-1)

如果您想使用模仿,我会选择这样的东西:

@Mock
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());

HTH!