如何在Moq中模拟没有参数的熔炉并填充 [英] How to mock a melthod with out paramter in Moq AND fill the out
问题描述
我在Stackoverflow中看到了有关最小起订量参数的几个问题,我的问题是如何填充此参数:让我们编写代码:
I have see several questions here in Stackoverflow about out parameters in MOQ, my question is how fill this parameter: Lets to code:
[HttpPost]
public HttpResponseMessage Send(SmsMoRequest sms)
{
if (sms == null)
return Request.CreateResponse(HttpStatusCode.BadRequest);
SmsMoResponse response;
_messageService.Process(sms, out response);
return Request.CreateResponse(HttpStatusCode.Created, response.ToString());
}
我要测试这篇文章:
[Test]
public void Should_Status_Be_Create_With_Valid_XML()
{
// Arrange
var messageServiceMoq = new Mock<IMessageService>();
SmsMoResponse response;
messageServiceMoq.Setup(mock => mock.Process(It.IsNotNull<SmsMoRequest>(), out response));
_kernel.Bind<IMessageService>().ToConstant(messageServiceMoq.Object);
var client = new HttpClient(_httpServer) { BaseAddress = new Uri(Url) };
// Act
using (var response = client.PostAsync(string.Format("Api/Messages/Send"), ValidContent()).Result)
{
// Asserts
response.IsSuccessStatusCode.Should().BeTrue();
response.StatusCode.Should().Be(HttpStatusCode.Created);
}
}
问题
发送方法(POST)中的我的response
对象用于后响应,但是_messageService.Process
负责填充response
对象.
在测试方法Should_Status_Be_Create_With_Valid_XML
中,我模拟了_messageService.Process
并且response
对象未填充Request.CreateResponse(HttpStatusCode.Created, response.ToString());
Problem
My response
object in Send method (POST) is used in post response but the _messageService.Process
is responsible to fill the response
object.
In test method Should_Status_Be_Create_With_Valid_XML
I mock _messageService.Process
and response
object is not fill ocorr error Null reference
in Request.CreateResponse(HttpStatusCode.Created, response.ToString());
response
为空!
推荐答案
当然response
为null,任何地方都没有代码可以将其设置为任何值(在您的服务方法或模拟中).
Of course response
is null, there's no code anywhere that would set it to anything (in your service method or your mock).
由于您正在嘲笑通常会填充它的方法,因此由您来指定设置方式.在调用Setup
之前,应使用期望作为调用该方法时的值来填充对象.
Since you're mocking the method that would usually fill it in, it's up to you to specify how it is set. You should fill in the object before calling Setup
with what you expect to be the value when that method is called.
此外,请参阅此问题以获取更多信息.
Also, see this question for more info.
这篇关于如何在Moq中模拟没有参数的熔炉并填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!