问题
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());
}
I want to test this post:
[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);
}
}
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
is null!
回答1:
Of course response
is null, there's no code anywhere that would set it to anything (in your service method or your mock).
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.
来源:https://stackoverflow.com/questions/25206450/how-to-mock-a-melthod-with-out-paramter-in-moq-and-fill-the-out