【问题标题】:How to mock constructor with methods as an parameter using EasyMock?如何使用 EasyMock 以方法作为参数来模拟构造函数?
【发布时间】:2019-12-31 07:51:00
【问题描述】:

我想使用 EasyMock 测试方法“make()”。在方法内部有一个使用参数创建的新对象。我想知道,如何使用 EasyMock 编写相同的测试用例?

private void make(final Parent p) {
    fun = new Fun(getMethod1(), getMethod2(), getMethod3(), getMethod4());
    fun.setBorder(120);
    p.add(fun);
}

private ProductSpecification getMethod1() {
    return getSequence();
}

//XYZ.class
@Override
public T getSequence() {
    return this.sequence;
}

public View getMethod2() {
    return view;
}

public Info getMethod3() {
    return this.info;
}

任何帮助将不胜感激。 谢谢。

【问题讨论】:

    标签: easymock


    【解决方案1】:

    你不能直接用 EasyMock 来做。有些人会告诉你,你可以使用 PowerMock 模拟实例化。

    但这通常意味着您的设计存在缺陷。我个人从不使用 PowerMock。

    要问的问题是:

    1. 我真的需要模拟那个实例化吗?如果只是一些数据,可能不需要
    2. 如果需要,我应该提取类还是方法?

    问题 2 的答案取决于您以后将如何使用它。

    如果我提取一个类,我将有

    private final FunFactory funFactory;
    private void make(Parent p) {
        fun = funFactory.create(getMethod1(), getMethod2(), getMethod3(), getMethod4());
        fun.setBorder(120);
        p.add(fun);
    }
    
    @Test
    public void test() {
        Fun fun = mock(Fun.class);
        FunFactory funFactory = mock(FunFactory.class);
        expect(funFactory.create("m1", "m2", "m3", "m4")).andReturn(fun);
        replay(fun, funFactory);
        // do the test
    }
    

    如果我提取一个方法,我将有以下内容。

    private void make(Parent p) {
        fun = createFun(getMethod1(), getMethod2(), getMethod3(), getMethod4());
        fun.setBorder(120);
        p.add(fun);
    }
    
    Fun createFun(String m1, String m2, String m3, String m4) {
        return new Fun(m1, m2, m3, m4);
    }
    
    @Test
    public void test() {
        Fun fun = mock(Fun.class);
        Make make = partialMockBuilder(Make.class)
            .addMockedMethod("createFun")
            .createMock();
        expect(make.createMock("m1", "m2", "m3", "m4")).andReturn(fun);
        replay(fun, make);
        // do the test
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      相关资源
      最近更新 更多