【问题标题】:EasyMock - how to mock private object instantiation and variableEasyMock - 如何模拟私有对象实例化和变量
【发布时间】:2018-05-10 15:07:17
【问题描述】:

我有以下类来测试模拟私有对象的创建,

    class TestClass {

    private Dialog dialog;

    private DialogChangeListener listener = new DialogChangeListener() {
        public void onChange(Event e) {
            String v = e.getValue();
            if (condition1) {
                // perform operation 1
            } else if (condition2) {
                // perform operation 2
            } else if (condition3) {
               // perform operation 3
            }
        }
    }

    public void openDialog() {
        if (condition1) {
            dialog = new Dialog(arg1, arg2, listener);
        } else if (condition2) {
            dialog = new Dialog(arg1, arg2, arg3, listener);
        } else if (condition3) {
            dialog = new Dialog(arg1, arg2, arg3, listener);
        }
    }
}

在上述场景中,如何使用 EasyMock 模拟私有 'Dialog' 变量及其实例化以及私有 'listener' 变量,以便在有条件的基础上继续其余操作。

【问题讨论】:

    标签: java swing junit mocking easymock


    【解决方案1】:

    我的回答分为三个部分。

    首先,您不能使用 EasyMock 模拟属性和实例化。这些情况很少需要,意味着您应该重构。

    其次,PowerMock 可以模拟实例化。它很强大,但实际上我自己从未使用过它。

    第三,在你的情况下,

    1. 我将添加一个构造函数,将侦听器作为参数。轻松嘲笑它
    2. 进行部分模拟并将对话创建提取到特定方法中。这是如果您真的需要将创作保留在那里。否则,我会把它移到某个工厂并模拟它。

    代码示例:

    public void openDialog() {
        if (condition1) {
            dialog = createDialog(listener, arg1, arg2);
        } else if (condition2) {
            dialog = createDialog(listener, arg1, arg2, arg3);
        } else if (condition3) {
            dialog = createDialog(listener, arg1, arg2, arg3);
        }
    }
    
    /* default scope to make it mockable */ Dialog createDialog(DialogChangeListener listener, Object... args) {
        //...
    }
    

    然后是测试:

    TestClass testClass = EasyMock.partialMockBuilder(TestClass.class)
            .addMockedMethod("createDialog")
            .createMock();
    expect(testClass.createDialog(listener, ...)).andReturn(someDialog);
    

    【讨论】:

      猜你喜欢
      • 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
      相关资源
      最近更新 更多