C# MVC、MOQ单元测试webapi方法
我一直遵循使用MOQ对webapi方法进行单元测试的常规模式。这次我有一个控制器方法,它有点不同,我不知道为什么测试失败 这是我们其中一种方法的标准外观。我们调用存储库并返回OK API方法C# MVC、MOQ单元测试webapi方法,c#,asp.net,unit-testing,model-view-controller,moq,C#,Asp.net,Unit Testing,Model View Controller,Moq,我一直遵循使用MOQ对webapi方法进行单元测试的常规模式。这次我有一个控制器方法,它有点不同,我不知道为什么测试失败 这是我们其中一种方法的标准外观。我们调用存储库并返回OK API方法 [HttpPost] public IHttpActionResult SampleMethod(SampleModel model) { var result= _myRepository.SampleMethod(model.Field1, model.Field
[HttpPost]
public IHttpActionResult SampleMethod(SampleModel model)
{
var result= _myRepository.SampleMethod(model.Field1, model.Field2);
return Ok();
}
[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();
}
我通常使用以下测试来进行类似的测试
单元测试
/// <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));
}
我得到的测试失败的错误消息是这样的,但是没有地方可以看到额外的异常信息
"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."
您确实设置了存储库,但不返回任何内容
mockRepository
.Setup(x => x.SampleMethod(It.IsAny<string>(), It.IsAny<string>()));
您没有设置它,因此,
emailSender
为空。实际上,我在示例中没有返回电子邮件项目,而是将其作为it.IsAny()返回。你创建了一个新项目,这就是它所做的。谢谢
mockRepository
.Setup(x => x.SampleMethod(It.IsAny<string>(), It.IsAny<string>())).Returns(new EmailItem{ToAddress = "", Subject = ""});
emailSender.BuildEmail(emailItem.ToAddress, emailItem.Subject);