另一个类中的模拟方法

问题描述 投票:0回答:1

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

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;
    }
}

这是我的测试用例

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);
    }
}

我的输出:

需要外部模拟

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

缺少什么?

依赖关系:

byte-buddy-1.10.11.jar
cglib-nodep-3.2.9.jar
hamcrest-core-1.3.jar
javassist-3.24.0-GA.jar
junit-4.12.jar
mockito-all-1.10.19.jar
mockito-core-2.23.0.jar
objenesis-3.0.1.jar
mocking mockito junit4
1个回答
0
投票

为了模拟对AnotherClass的调用,您不应在应用程序代码内使用new创建实例。这将始终实例化real对象,您将无法对其进行模拟。

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

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;
    }
}

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

© www.soinside.com 2019 - 2024. All rights reserved.