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 方法来自另一个类。我应该怎么做才能消除此方法的依赖关系,请注意提供给此方法的值是动态获取的。
我认为你应该StateMachine.checkFormatRoman
嘲笑你的静态方法。您可以使用powermock来执行此操作。
您可以返回所需的值。
类似的东西..
PowerMockito.mockStatic(StateMachine.class);
PowerMockito.when(StateMachine.checkFormatRoman(5, "IIIIL")).thenReturn(true);
我认为StateMachine.checkFormatRoman
是static
.您可以按如下方式重新设计:
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);
创建实例来创建具有虚拟实现的状态机。
替代方法:
重新设计您正在测试的类,以便您可以指定要调用哪个函数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 的依赖。