如何测试apicontroller?

时间:2013-11-21 07:06:22

标签: c# unit-testing asp.net-web-api

我尝试为我的控制器编写一些单元测试。

[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; }
}

RegistrationSocialRequest只是模型绑定所需的POCO对象。这个方法返回json,我想跟踪它的变化,只是为了确保客户端可以使用它。为了测试我使用Moq和MSTest。这是测试方法。

[TestMethod]
public void IsJsonOkRegistrationSocial()
{
    //Arrange
    Mock<IUserProvider> mock = new Mock<IUserProvider>();
    mock.Setup(m => 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));
}

但是方法抛出异常,因为UserIP为null,我不能理解为什么。我是单元测试的新手,也许这一切都可以更简单的方式完成。

1 个答案:

答案 0 :(得分:1)

在运行单元测试时,在Web环境之外运行代码时,未按预期设置HttpContext.Current.Request.UserHostAddress。

解决方法是使用方法'GetUserIP'创建'IHttpContextService'。通过这种方式,您可以在UserIP属性中调用此服务,并且在测试时可以模拟接口。