title: How to test apicontroller?
body: <p>I try to write some unit tests for my controller.</p>
  
  <pre><code>[HttpPost]
  public Answer RegistrationSocial([FromBody] RegistrationSocialRequest newUser)
  {
      var answer = new Answer();
      try
      {
          userProvider.RegistrationSocial(newUser.Email, 
                                          newUser.PhoneNumber,
                                          newUser.SocialProviderId,
                                          newUser.SocialProvider, 
                                          UserIP);
          answer.Result = 0;
      }
      catch (Exception e)
      {
          answer.Result = 2;
          answer.Description = "Server error";
      }
      return answer;
  }
  
  private string UserIP
  {
      get { return HttpContext.Current.Request.UserHostAddress; }
  }
  </code></pre>
  
  <p>RegistrationSocialRequest is just a POCO object which is needed for Model Binding. This method return json and I want to track its change, just to be sure that clients can work with it. For testing I use Moq and MSTest. Here is the test method.</p>
  
  <pre><code>[TestMethod]
  public void IsJsonOkRegistrationSocial()
  {
      //Arrange
      Mock&lt;IUserProvider&gt; mock = new Mock&lt;IUserProvider&gt;();
      mock.Setup(m =&gt; m.RegistrationSocial("lincoln@usa.gov", 
                                           "123", 
                                           "0987654321",
                                            1, 
                                            "192.0.0.1"));
  
      UserController controller = new UserController(mock.Object);
      Answer answerOk = new Answer
      {
          Result = 0,
          Caption = "Ok",
          Description = null,
          Data = null
      };
  
      //Action
      var answer = controller.RegistrationSocial(new RegistrationSocialRequest
      {
          SocialProvider = 1,
          Email = "lincoln@usa.gov",
          PhoneNumber = "123",
          SocialProviderId = "0987654321"
      });
  
      //Assert
      Assert.AreEqual(JsonConvert.SerializeObject(answerOk),
                      JsonConvert.SerializeObject(answer));
  }
  </code></pre>
  
  <p>But method thrown exception, because UserIP is null, and I can`t undestand why. I am new in unit testing, maybe this all could be done in easier way.</p>