Junit测试用例的依赖性删除

时间:2012-11-22 08:57:06

标签: java

Matcher m = Pattern.compile("(" + genusNames + ")[^\\p{L}][^\uFF00]").matcher(inputText);
        while(m.find()){
            if(!StateMachine.checkFormatRoman(m.group(1).length(), m.start()))
                createDecision(m.group(1), "<Roman>" + m.group(1) + "</Roman>", m.start());
    }

在上面的代码中,checkFormatRoman方法来自另一个类。如何删除此方法的依赖性,请注意,此方法提供的值是动态获得的。

2 个答案:

答案 0 :(得分:1)

我认为你应该嘲笑你的静态方法StateMachine.checkFormatRoman。您可以使用powermock

执行此操作

您可以返回所需的值。

像...这样的东西。

PowerMockito.mockStatic(StateMachine.class);
PowerMockito.when(StateMachine.checkFormatRoman(5, "IIIIL")).thenReturn(true);

答案 1 :(得分:0)

我认为StateMachine.checkFormatRomanstatic。您可以按如下方式重新设计:

class StateMachine {
    static class Implementation implements ImplementationInterface {
        ...
    }

    ImplementationInterface impl;

    public StateMachine () {
        impl = new Implementation ();
    }

    public StateMachine (ImplementationInterface alternative) {
        impl = alternative;
    }

    public ... checkFormatRoman (...) {
        return impl.checkFormatRoman (...);
    }
}

现在,您可以通过使用machine = new StateMachine (dummyImplementation);创建实例来进行测试,创建具有虚拟实现的StateMachine。

替代方法:

重新设计您正在测试的课程,以便您可以指定要为checkFormatRoman调用的函数:

class MyClass { // the class you are testing
    public interface Helpers {
        ... checkFormatRoman ...
    }

    static class HelpersDefault implements Helpers {
        ... checkFormatRoman ... {
            return StateMachine.checkFormatRoman (...);
        }
    }

    Helpers helpers = new HelpersDefault ();

    public void setHelpers (Helpers alternativeHelpers) {
        helpers = alternativeHelpers;
    }

    ... // your methods, calling, e.g., helpers.checkFormatRoman instead of
    // StateMachine.checkFormatRoman
}

// testing
...
objToTest = new MyClass ();
objToTest.setHelpers ( new MyClass.Helpers {
   // ... test dummy implementation of checkFormatRoman goes here
});

或者通过定义StateMachine的接口并在构造时传递状态机参数来完全删除类与StateMachine的依赖关系。

相关问题