很遗憾,您正在使用 getResultState() 创建 ResultState 对象本身,这实际上是您的障碍。考虑重构为以下接口:
protected ResultState initResultState ( )
{
this.resultState = new ResultState();
// Initialization Logic...
return this.resultState;
} // END initResultState
public ResultState getResultState ( )
{
if ( this.resultState === null )
{
return this.initResultState();
}
return this.resultState;
} // END getResultState()
从这个位置,更容易测试你的 getter 方法。定义一个后代类,它返回一个已知的ResultState Stub for initResultState(),可以查询,即:
/**
* The test fixutre's initResultState() method merely returns a simple Stub of
* the ResultState object, which can be more easily interrogated.
*/
public ResultState initResultState ( )
{
return new Stub_ResultState();
} // END initResultState
当然,您仍然可以使用受保护的initResultState()。考虑以下重构:
protected ResultState initResultState ( ResultState newResultState )
{
this.resultState = newResultState;
// Initialization Logic...
return this.resultState;
} // END initResultState
public ResultState getResultState ( )
{
if ( this.resultState === null )
{
return this.initResultState( new ResultState() );
}
return this.resultState;
} // END getResultState
这允许您覆盖后代类中的getResultState() 方法,以便您可以传递另一个ResultState Stub 对象以在之后进行操作和询问,例如:
/**
* The test fixture's getResultState() method always acts as a passthrough for
* initResultState(), which is protected, so that the output of the protected
* method can be interrogated.
*/
public ResultState getResultState ( )
{
return this.initResultState( new Stub_ResultState() );
} // END getResultState
从这个位置开始,您需要 两个 测试夹具:一个覆盖 initResultState() 的行为以测试 getter 的功能;另一个覆盖getResultState() 的行为以测试initResultState() 的行为。两者都使用Stub_ResultState 类的实例,它必然是ResultState 类的后代,但提供对其父对象内部值的公共访问,以便在单元测试中进行查询。
我希望这是有道理的,但请随时要求澄清。