我一直遵循使用MOQ测试我的Web方法的常规模式。这一次,我有一个有点不同的控制器方法,我不知道为什么测试失败。
这是我们其中一种方法的标准外观。我们调用存储库并返回OK。
API方法
[HttpPost]
public IHttpActionResult SampleMethod(SampleModel model)
{
var result= _myRepository.SampleMethod(model.Field1, model.Field2);
return Ok();
}对于这种情况,我通常使用以下测试。
单元测试
/// <summary>
/// Tests the SampleMethod is run
/// </summary>
[TestMethod]
public void SampleMethod_Is_Run()
{
//Arrange
mockRepository
.Setup(x => x.SampleMethod(It.IsAny<string>(), It.IsAny<string>()))
.Returns(It.IsAny<EmailItem>()); //forgot to add this the first time
var controller = new MyController(mockRepository.Object);
//Act
controller.SampleMethod(It.IsAny<string>(), It.IsAny<string>());
//Assert
mockRepository.VerifyAll();
}
/// <summary>
/// Tests the SampleMethod returns correct status code
/// </summary>
[TestMethod]
public void SampleMethod_Returns_OK()
{
//Arrange
mockRepository
.Setup(x => x.SampleMethod(It.IsAny<string>(), It.IsAny<string>()))
.Returns(It.IsAny<EmailItem>()); //forgot to add this the first time;
var controller = new MyController(mockRepository.Object);
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
//Act
var response = controller.SampleMethod(It.IsAny<string>(), It.IsAny<string>());
//Assert
Assert.IsInstanceOfType(response, typeof(OkResult));
}现在,假设我有这样一个方法,它调用另一个类发送电子邮件。为什么那些单元测试不能继续工作了?
新API方法
[HttpPost]
public IHttpActionResult SampleMethod(SampleModel model)
{
var emailItem= _myRepository.SampleMethod(model.Field1, model.Field2);
//With this additional code, the test will fail
EmailSender emailSender = new EmailSender();
emailSender.BuildEmail(emailItem.ToAddress, emailItem.Subject);
return Ok();
}我得到的关于测试失败的错误消息是这样的,但是在哪里看不到额外的异常信息。
"System.Web.Http.HttpResponseException: Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by 'Response' property of this exception for details."发布于 2017-06-28 13:42:03
您确实设置了存储库,但不返回任何内容。
mockRepository
.Setup(x => x.SampleMethod(It.IsAny<string>(), It.IsAny<string>()));你应该试着:
mockRepository
.Setup(x => x.SampleMethod(It.IsAny<string>(), It.IsAny<string>())).Returns(new EmailItem{ToAddress = "", Subject = ""});你在努力阅读
emailSender.BuildEmail(emailItem.ToAddress, emailItem.Subject);您没有设置它,所以emailSender是空的。
https://stackoverflow.com/questions/44803961
复制相似问题