【问题标题】:Easymock new object and handle its function call (No PowerMock)Easymock 新对象并处理其函数调用(无 PowerMock)
【发布时间】:2017-07-18 05:36:38
【问题描述】:

我有一个需要进行单元测试的类。结构如下:

public class classToBeTested{
    public returnType function1(){
        //creation of variable V
        return new classA(V).map();
    }
}

classA类如下:

public class classA{
    //Constructor
    public returnType map(){
        //Work
    }
}

我正在使用 FunSuite、GivenWhenThen 和 EasyMock 在 Scala 中创建单元测试。
我的测试结构如下:

class classToBeTested extends FunSuite with GivenWhenThen with Matchers with EasyMockSugar {
    test(""){
        Given("")
        val c = new classToBeTested()
        expecting{
        }
        When("")
        val returnedResponse = c.function1()
        Then("")
        //checking the returned object
    }
}

期望中我需要写什么?
我该如何处理上述情况?

注意:不能使用 PowerMock。

回答: 谢谢,@亨利。经过大量搜索以及@Henri 重构代码提供的答案是处理这种情况的最佳方法。原因如下:

单元测试不能模拟由new 调用创建的对象(没有PowerMock)。因此,为了测试代码,我们需要根据要测试的类(这里是classToBeTested)中正在使用的类(这里是classA)中存在的条件编写单元测试。因此,在测试classToBeTested时,我们需要了解classA的功能和结构,并分别创建测试用例。

现在测试用例依赖于classA 中的方法结构,这意味着classToBeTestedclassA 是紧密耦合的。因此,通过 TDD 方法,我们需要重构代码。
在上面的例子中:
而不是使用

classA object = new classA(V);

最好将对象提供给方法(例如:在 Spring MVC 中自动装配classA object)。

接受建议。另外,如果有人可以给出更好的解释,请这样做。

【问题讨论】:

    标签: scala unit-testing mocking scalatest easymock


    【解决方案1】:

    你不能。您要模拟的内容的实例化在您要测试的类中。因此,如果没有 powermock,您需要进行重构才能使其正常工作。

    至少是将类创建提取到另一个方法中

    public class classToBeTested{
        public returnType function1(){
            //creation of variable V
            return getClassA(V).map();
        }
    
        protected classA getClassA(VClass v) {
            return new classA(v);
    }
    

    然后,您可以进行部分模拟。我不知道如何在scala中做到这一点,所以下面的代码可能是错误的,但我希望你能明白。

    class classToBeTested extends FunSuite with GivenWhenThen with Matchers with EasyMockSugar {
        test(""){
            Given("")
            val c = partialMockBuilder(classToBeTested.class).addMockedMethod("getClassA").build()
            val a = mock(classA.class)
            expecting{
                expect(c.getClassA()).andReturn(a)
                expect(a.map()).andReturn(someReturnType)
            }
            When("")
            val returnedResponse = c.function1()
            Then("")
            //checking the returned object
            // whatever you need to check
        }
    }
    

    【讨论】:

    • 我没有尝试部分模拟方法。但是重构是没有 powermock 的最佳选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多