我假设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 的依赖。