如何测试mvc控制器的状态代码

时间:2016-10-06 12:57:52

标签: c# asp.net-mvc unit-testing

我正在为我的控制器使用原生的.net visual studio测试工具。试图确保在此时(代码的最开始)如果传递给控制器​​的内容未通过授权,则会收到未经授权的状态代码集。这是我的控制器代码。

public class HubspotController : Controller
{
    [HttpPost]
    public ActionResult FreeDemo(string json)
    {
        JObject jobject = JObject.Parse(json);

        var password = jobject["person"]["password"]?.ToString();
        var username = jobject["person"]["username"]?.ToString();

        if (!AuthorizeUser(password, username))
        {
            StatusUnauthorized();
        }

        var resultStatus = new ResultStatus { Message = "success"};
        return Json(resultStatus, JsonRequestBehavior.AllowGet);
    }

    public ActionResult StatusUnauthorized()
    {
        return new HttpStatusCodeResult((int)HttpStatusCode.Unauthorized, "Unauthorized");
    }

    private bool AuthorizeUser(string password, string username)
    {
        return false;
    }
}

这是我的考验。忍受我,我没有太多的测试经验所以只是想弄清楚这一点。

[TestClass]
public class HubspotControllerFixture
{
    private Mock<HttpRequestBase> request;
    private Mock<HttpContextBase> httpContext;
    private Mock<HttpResponseBase> response;

    [TestInitialize]
    public void TestInitialize()
    {
        request = new Mock<HttpRequestBase>();
        request.SetupGet(r => r.ContentType).Returns("application/json");
        response = new Mock<HttpResponseBase>();
        httpContext = new Mock<HttpContextBase>();
        httpContext.SetupGet(c => c.Request).Returns(request.Object);
        httpContext.SetupGet(x => x.Response).Returns(response.Object);
    }

    [TestMethod]
    public void Status_Code_Gets_Set_To_Unauthorized()
    {
        var json = "{\"person\": {\"password\":\"abc123\", \"username\":\"user\", \"name\":\"test person\"}}";
        var controller = new HubspotController()
        {
            ControllerContext = new ControllerContext()
            {
                HttpContext = httpContext.Object
            }
        };
        controller.FreeDemo(json);
        Assert.AreEqual(HttpStatusCode.Unauthorized, httpContext.Object.Response.StatusCode);
    }
}

当我运行时,我收到错误。我究竟做错了什么?

  

Assert.AreEqual失败。预期:<Unauthorized (System.Net.HttpStatusCode)>。实际:<0 (System.Int32)>

2 个答案:

答案 0 :(得分:1)

您在测试中声明了错误的对象。此测试用例对HttpContext没有影响或依赖。您可能希望断言测试方法的结果。

首先需要更新目标控制器操作。

//...other code omitted for brevity
if (!AuthorizeUser(password, username))
{
    return StatusUnauthorized();
} 
//...other code omitted for brevity

你的Test现在看起来像这样,因为你实际上不需要为这个测试用例提供模拟的HttpContext

[TestMethod]
public void Status_Code_Gets_Set_To_Unauthorized() {
    //Arrange
    var json = "{\"person\": {\"password\":\"abc123\", \"username\":\"user\", \"name\":\"test person\"}}";
    var controller = new HubspotController();
    var expected = (int)HttpStatusCode.Unauthorized;
    //Act
    var actionResult = controller.FreeDemo(json) as HttpStatusCodeResult;
    //Assert
    Assert.IsNotNull(actionResult);
    Assert.AreEqual(expected, actionResult.StatusCode);
}

答案 1 :(得分:0)

我认为你错过了一份回复声明。请参阅下面的更新代码。

public class HubspotController : Controller
{
    [HttpPost]
    public ActionResult FreeDemo(string json)
    {
        JObject jobject = JObject.Parse(json);

        var password = jobject["person"]["password"]?.ToString();
        var username = jobject["person"]["username"]?.ToString();

        if (!AuthorizeUser(password, username))
        {
            return StatusUnauthorized();
        }

        var resultStatus = new ResultStatus { Message = "success"};
        return Json(resultStatus, JsonRequestBehavior.AllowGet);
    }

    public ActionResult StatusUnauthorized()
    {
        return new HttpStatusCodeResult((int)HttpStatusCode.Unauthorized, "Unauthorized");
    }

    private bool AuthorizeUser(string password, string username)
    {
        return false;
    }
}