【问题标题】:Mock Method inside another class另一个类中的模拟方法
【发布时间】:2020-06-14 09:59:50
【问题描述】:

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

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】:

    要模拟对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;
        }
    }
    

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

    【讨论】:

    • 谢谢你的建议,但是在 PowerMockito 的帮助下,我可以模拟这个或者 powermockito 是不好的做法吗?
    • 一种更简洁的方法是遵循控制反转并利用依赖注入。我认为 PowerMockito 很可能是一种不好的做法,因为这可能会导致您的应用程序设计不佳
    猜你喜欢
    • 2019-07-29
    • 2013-06-04
    • 2014-05-05
    • 1970-01-01
    • 2015-10-14
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多