我使用Rhino Mocks版本3.6,我发现here的答案在我的案例中不起作用:
[TestMethod()]
public void Test()
{
IConnected connectable = MockRepository.GenerateStub<IConnected>();
connectable.Stub(c => c.Connect()).Do(new Action(() =>
{
bool test = false;
if (!test)
test = true;
})).Repeat.Any();
connectable.Stub(c => c.Connect()).Do(new Action(() => { })).Repeat.Any();
}
我有一个InvalidOperationException:IConnected.Connect()的结果;已经安装好了。
我用stub和mock测试它,我得到了相同的结果。
我用属性进行了相同的测试,但它也没有用。
[TestMethod()]
public void Test()
{
IConnected connectable = MockRepository.GenerateStub<IConnected>();
connectable.Stub(c => c.IsConnected).Return(true).Repeat.Any();
connectable.Stub(c => c.IsConnected).Return(false).Repeat.Any();
}
它是Rhino Mocks的糟糕版本还是有回归?
唯一有效的方法是清除所有期望,但我必须将所有期望重置为相同的值:
// clear expectations, an enum defines which
_stubRepository.BackToRecord(BackToRecordOptions.All);
// go to replay again.
_stubRepository.Replay();
我的IConnected界面:
/// <summary>
/// Represents connected component management interface.
/// </summary>
public interface IConnected
{
/// <summary>
/// Gets the connection status.
/// </summary>
ConnectionState ConnectionStatus { get; }
/// <summary>
/// Gets a value indicating whether this instance is connected.
/// </summary>
/// <value>
/// <c>true</c> if this instance is connected; otherwise, <c>false</c>.
/// </value>
bool IsConnected { get; }
/// <summary>
/// Occurs when [connection state changed].
/// </summary>
event EventHandler<ConnectionStateChangeEventArgs> ConnectionStateChanged;
/// <summary>
/// Connects this instance.
/// </summary>
void Connect();
/// <summary>
/// Disconnects this instance.
/// </summary>
void Disconnect();
/// <summary>
/// Occurs when [reconnect].
/// </summary>
event EventHandler<ConnectionRetryEventArgs> RetryConnection;
}
答案 0 :(得分:0)
您可以通过Do()
处理程序为存根实现某些行为
以下是针对您案例的解决方案:
var isConnected = false;
var stub = MockRepository.GenerateStub<IConnected>();
stub
.Stub(c => c.IsConnected)
.Do((Func<bool>)(() => isConnected))
.Return(false);
stub
.Stub(c => c.Connect())
.Do((Action)(() => { isConnected = true; }));
现在只是测试:
Console.WriteLine(stub.IsConnected);
stub.Connect();
Console.WriteLine(stub.IsConnected);
但如果你重新设计你的测试以避免在你需要这样一个复杂的存根(如果有可能的话,是cource)的情况下会好得多。可能将测试分成几个测试可能是合适的。