[英]RhinoMocks - when a method is called n times, how to test its parameters in the n - k call
我有一個方法,它恰好調用另一種方法4次,每次使用不同的參數。 我想寫了4個不同的單元測試用例來檢查方法,每個調用都有一個特定的值。
以下是我的方法的外觀:
public void MainMethod()
{
IServiceProvider serviceProvider = GetServiceProvider();
string value1 = GetValueFromStorage("SomeArg1");
// Call AnotherMethod
serviceProvider.AnotherMethod(value1);
string value2 = GetValueFromStorage("SomeArg2");
// Call AnotherMethod
serviceProvider.AnotherMethod(value2);
string value3 = GetValueFromStorage("SomeArg3");
// Call AnotherMethod
serviceProvider.AnotherMethod(value3);
string value4 = GetValueFromStorage("SomeArg4");
// Call AnotherMethod
serviceProvider.AnotherMethod(value4);
}
這是我的測試方法:
public void TestMainMethod()
{
// Stub storage
IDataStorage dataStorage = MockRepository.GenerateStub<IDataStorage>();
// Stub serviceProvider
IServiceProvider dataStorage =
MockRepository.GenerateStub<IServiceProvider>();
// stub for SomeArg1
dataStorage.Stub(x => x.GetValueFromStorage(null)
.IgnoreArguments().Return("Value1"))
.Repeat.Once();
// stub for SomeArg2
dataStorage.Stub(x => x.GetValueFromStorage(null)
.IgnoreArguments().Return("Value2"))
.Repeat.Once();
// stub for SomeArg3
dataStorage.Stub(x => x.GetValueFromStorage(null).IgnoreArguments()
.Return("Value3")).Repeat.Once();
// stub for SomeArg4
dataStorage.Stub(x => x.GetValueFromStorage(null).IgnoreArguments()
.Return("Value4")).Repeat.Once();
// call MainMethod
MainMethod();
// Assert that third call is called with "Value3"
serviceProvider.AssertWasCalled(x => x.AnotherMethod("Value3"));
}
這似乎是我不能忽略其他調用,只是驗證第三個調用是用一個特定的參數調用的(或者對於序列中的任何其他調用)。 似乎我必須四次調用“AssertWasCalled”並按順序檢查個別參數。 那我怎么能做到這一點? 或者我在這里遺漏了什么?
我認為你可以使用GetArgumentsForCallsMadeOn(Action<T>)
。 很長一段時間以來我使用它但它給你一個列表,其中包含一組對象,這些對象是每個調用的調用參數。
如果RhinoMocks支持Moq的Callback語法,你可以為IServiceProvider.AnotherMethod實現一個Callback(或等效的),並讓該回調將AnotherMethod的參數放入一個列表供以后檢查。 在Moq中有這樣的事情:
var anotherMethodParams = new List<string>();
var serviceProvider = new Mock<IServiceProvider>();
//Setup in Moq seems to be somewhat analogous to Stub in RhinoMocks
serviceProvider.Setup(sp => sp.AnotherMethod(It.IsAny<string>()))
.Callback((string s) => { anotherMethodParams.Add(s); }));
var x = GetTheObjectThatWillCallServiceProviderAnotherMethod();
x.GetValueFromStorage("Value1");
x.GetValueFromStorage("Value2");
x.GetValueFromStorage("Value3");
//Assert that the parameter to the second call of AnotherMethod is as expected.
Assert.AreEqual("Value2", anotherMethodParams[1]);
對於Moq示例感到抱歉,但這就是我所熟悉的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.