gpt4 book ai didi

c# - Rhino Mocks 不抛出异常

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:08 28 4
gpt4 key购买 nike

我试图从测试中抛出异常,(使用 rhino 和 nunit),但它没有按预期工作

接口(interface)

public interface IEmailService
{
void SendEmail(string to, string subject, string body);
}

public interface IWebService
{
void LogError(string message);
}

public class MockService : IWebService
{
public string LastError;

public void LogError(string message)
{
LastError = message;
}
}

public class LogAnalyzerDynamicMockWithEmail
{
public IWebService Service { get; set; }
public IEmailService Email { get; set; }

public void Analyze(string fileName)
{
try
{
if (fileName.Length < 8)
Service.LogError("Filename too short:" + fileName);
}
catch (Exception exception)
{
Email.SendEmail("a", "subject", exception.Message);
}
}
}

这是测试方法

[Test]
public void Analyze_WebServiceThrows_SendsEmail()
{
var mockRepository = new MockRepository();
var stubWebService = mockRepository.Stub<IWebService>();
var mockEmailService = mockRepository.StrictMock<IEmailService>();

var logAnalyzerDynamicMockWithEmail = new LogAnalyzerDynamicMockWithEmail
{
Service = stubWebService,
Email = mockEmailService
};

stubWebService.Stub(m => m.LogError("whatever")).IgnoreArguments().Throw(new Exception("fake exception"));


Assert.Throws<Exception>(() => { logAnalyzerDynamicMockWithEmail.Analyze("abc.ext"); });
mockEmailService.AssertWasCalled(m => m.SendEmail("a", "subject", "fake exception"));

}

但测试失败,消息为“Expected: <system.exception>, but was: null

谁能帮我指出我在这里遗漏了什么?

最佳答案

我不确定为什么你的模拟没有抛出异常,但我建议使用更新的 RhinoMock 语法(不需要实例化 MockRepository。)此外,你的 Assert.Throws 调用将不起作用,因为你的代码正在捕获异常。 Assert.Throws 仅在异常未被捕获时才有用。

这是一个工作示例。请注意,我将 SendEmail 预期移动到您的 Analyze 调用之上。无论模拟中的期望值有多少,调用 VerifyAllExpectations 都将确保它们得到满足。

[Test]
public void Analyze_WebServiceThrows_SendsEmail_Modified()
{
var stubWebService = MockRepository.GenerateMock<IWebService>();
var mockEmailService = MockRepository.GenerateMock<IEmailService>();

var logAnalyzerDynamicMockWithEmail = new LogAnalyzerDynamicMockWithEmail
{
Service = stubWebService,
Email = mockEmailService
};

// Set up our expectations
stubWebService.Expect(m => m.LogError("whatever")).IgnoreArguments().Throw(new Exception("fake exception"));
mockEmailService.Expect(m => m.SendEmail("a", "subject", "fake exception")).Repeat.Once();

logAnalyzerDynamicMockWithEmail.Analyze("abc.ext");

// Verify our SendEmail method was called
mockEmailService.VerifyAllExpectations();
}

关于c# - Rhino Mocks 不抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40263075/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com