[英]Rhino Mocks : How to change expectation on method, property or field without clear all expectation?
我使用的是Rhino Mocks 3.6版,在這種情況下,我在這里找不到答案:
[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();的結果; 已經設置好了。
我用存根和模擬測試了它,並且得到了相同的結果。
我對屬性進行了相同的測試,但它也不起作用。
[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;
}
您可以通過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);
但是,如果您重新設計測試以免需要復雜的存根(如果可能的話),那會更好。 可能將測試拆分為更多的測試可能是合適的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.