I am writing unit tests for the existing Web API 2 project. For which i am using Ploeh Autofixture
and Moq
.
Test Method : UPDATED
[Test]
public async Task Service1_TestMethod() {
//some code here
var fakeemail = FakeBuilder.Create<string>("[email protected]");
var fakeUserInvite =
FakeBuilder.Build<UserInvite>()
.With(i => i.EmailAddress, fakeemail)
.With(i => i.Username, fakeemail)
.Create();
var fakeUserToken = FakeBuilder.Create<string>();
var fakeHttpResponseMessage =
Fixture.Build<HttpResponseMessage>()
.With(h => h.StatusCode, HttpStatusCode.OK).Create();
//Here i am mocking another service method. Whose response is HttpResponseMessage.
Service2.Setup(i => i.AddUser(fakeUserInvite, fakeUserToken))
.ReturnsAsync(fakeHttpResponseMessage);
var result = await Service1.AddUser( /* */);
}
Service1 Method :
public async Task<bool> AddUser(/* */)
{
var response = await Service2.AddUser(userInvite, userToken); // response is null even after mocking it.
// Add user code follows bassed on the above response.
}
If i comment the Service2.AddUser
call then everything works. There is a lot of code in that method apart from this call. I am having problem with only this call. If this call returns the mocked HttpResponseMessage
then everything works.
Service2
is an external API. I am just wondering how to mock
HttpResponseMessage
. Any help is appreciated.
response
is null for the callService2.AddUser
. I want theresponse
to be the objectfakeHttpResponseMessage
which i mocked whilesetup
the call. – PuklichfakeUserInvite
andfakeUserToken
being passed to theService2.AddUser
method? The actual call being made needs to use those same objects in order for Moq to return yourfakeHttpResponseMessage
. See matching arguments in the Moq documentation. – MadraAutoFixture
and passed toService2.AddUser
. Those 2 parameters are valid types otherwiseService2.Setup
will throw compile time error. Updating question with these objects creation. – PuklichService2.AddUser
a static method? If not, how is theService2
test double being passed toService1
? – MadraService2.AddUser
is not a static method.Service2
is a Mock of originalService2
, which is injected toService1
throughUnity
. – PuklichService2
has other methods which return types other thanHttpResponseMessage
. They are working fine. OnlyAddUser
method is giving problem as it is returningHttpResponseMessage
. I think there is something tricky in mockingHttpResponseMessage
– Puklich