jeudi 18 août 2016

Mock HttpResponseMessage while unit testing API with Moq and AutoFixture

I am writing unit tests for the existing Web API 2 project. For which i am using Ploeh Autofixture and Moq.

Test Method :

[Test]
public async Task Service1_TestMethod() {

  //some code here
 var fakeemail = FakeBuilder.Create<string>("test1234@test.com");
  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.

Aucun commentaire:

Enregistrer un commentaire