1
我試圖測試類似於下面的例子類:部分嘲諷 - 預期被忽略(犀牛嘲笑)
public class Service : IService
{
public string A(string input)
{
int attemptCount = 5;
while (attemptCount > 0)
{
try
{
return TryA(input);
}
catch (ArgumentOutOfRangeException)
{
attemptCount--;
if (attemptCount == 0)
{
throw;
}
// Attempt 5 more times
Thread.Sleep(1000);
}
}
throw new ArgumentOutOfRangeException();
}
public string TryA(string input)
{
// try actions, if fail will throw ArgumentOutOfRangeException
}
}
[TestMethod]
public void Makes_5_Attempts()
{
// Arrange
var _service = MockRepository.GeneratePartialMock<Service>();
_service.Expect(x=>x.TryA(Arg<string>.Is.Anything)).IgnoreArguments().Throw(new ArgumentOutOfRangeException());
// Act
Action act =() => _service.A("");
// Assert
// Assert TryA is attempted to be called 5 times
_service.AssertWasCalled(x => x.TryA(Arg<string>.Is.Anything), opt => opt.Repeat.Times(5));
// Assert the Exception is eventually thrown
act.ShouldThrow<ArgumentOutOfRangeException>();
}
局部嘲諷似乎並不接受我的期望。當我運行測試時,我收到有關輸入的錯誤。當我調試時,我看到該方法的實際執行正在執行,而不是預期。
我正在做這個測試嗎?根據文檔(http://ayende.com/wiki/Rhino%20Mocks%20Partial%20Mocks.ashx):「部分模擬會調用在類上定義的方法,除非您定義了該方法的期望值。如果您已經定義了期望值,它將使用此常規規則。」
我認爲'TryA'應該是虛擬的 – Steve
@Steve,這似乎解決了這個問題。我寧願不必爲該功能添加虛擬功能,但我認爲它很少會發生。謝謝! –