我需要对类的公共接口方法进行单元测试,但是定义的行为依赖于私有状态变量。像这样:
private enum _state;
public void Connect()
{
if (_state == AlreadyConnected)
throw Exception;
(... do more things ...)
}
在这种情况下,我想确保在状态已经是特定值时调用方法时抛出正确的异常,但是如果状态字段是私有的,我该如何设置它呢?
答案 0 :(得分:2)
在您的情况下,私人状态表示对实体执行的操作的结果及其对操作的反应 所以,测试看起来像:
[Test]
public void Connect_throws_exception_if_already_connected()
{
var foo = new Foo();
foo.Connect();
Exception thrownExc = null;
try
{
foo.Connect();
}
catch(InvalidOperationException exc)
{
thrownExc = exc;
}
Assert.IsNotNull(thrownExc, "It was expected to get exception on 2nd connect attempt, but nothing were thrown.");
}