另一个类中的模拟方法

时间:2020-06-14 09:59:50

标签: mocking mockito junit4

这里我试图监视一个方法,因为它从外部调用了另一个方法。我所需要的只是模拟外部方法。下面是我对项目类型的遗留项目的模拟

sub-query

这是我的测试用例

public class TestClass {
    public int dependencyOne(){
        System.out.println("Need to mock Externally ");
        return  100;
    }
    public int methodNeedTobeTested(int a){
        int c = new AnotherClass().dependencyTwo();
        return a + this.dependencyOne() + c;
    }
}

public class AnotherClass {
    public int dependencyTwo(){
        System.out.println("Need to mock externally");
        return 100;
    }
}

我的输出:

需要在外部进行模拟

java.lang.AssertionError: 预期:30 实际:120

缺少什么?

依赖性:

public class TestClassTest {
    @InjectMocks
    TestClass testClass;

    @Mock
    AnotherClass anotherClass;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    @Rule
    public MockitoRule initRule = MockitoJUnit.rule();

    @Test
    public void methodNeedTobeTested() {
        testClass = Mockito.spy(new TestClass());
        Mockito.when(anotherClass.dependencyTwo()).thenReturn(10);
        Mockito.doReturn(10).when(testClass).dependencyOne();
        assertEquals(testClass.methodNeedTobeTested(10),30);
    }
}

1 个答案:

答案 0 :(得分:1)

要模拟对AnotherClass的调用,请勿在应用程序代码中使用new创建实例。这将始终实例化 real 对象,而您将无法对其进行模拟。

更好的方法是将AnotherClass的实例作为TestClass的构造函数的一部分,并遵循控制权的反转(例如,使用CDI的Spring Framework进行依赖注入)。

public class TestClass {

    public AnotherClass anotherClass;

    public TestClass(AnotherClass anotherClass) {
       this.anotherClass = anotherClass;
    }

    public int dependencyOne(){
        System.out.println("Need to mock Externally ");
        return  100;
    }

    public int methodNeedTobeTested(int a){
        int c = anotherClass.dependencyTwo();
        return a + this.dependencyOne() + c;
    }
}

使用这种方法,您的测试应该可以进行。