单元测试ApiController方法,状态代码不在HttpStatusCode枚举中

时间:2016-05-12 18:47:51

标签: c# asp.net moq

我有一个看起来像这样的ApiController方法......

    [HttpPost]
    public IHttpActionResult Post([FromBody] GloballyEnumeratedMessage gem)
    {
        var result = _gemPublisher.PublishGem(gem);

        if (result.Success)
        {
            return Ok();
        }

        return new StatusCodeResult((HttpStatusCode)422, this);
    }

我检查Ok结果的测试如下。

    [TestMethod]
    public void Post_ValidGem_Returns200()
    {
        _gemPublisherMock.Setup(v => v.PublishGem(It.IsAny<GloballyEnumeratedMessage>())).Returns(ResultStatus.FromSuccess());

        var controller = new PublishGemController(_gemPublisherMock.Object);

        // Act
        IHttpActionResult actionResult = controller.Post(It.IsAny<GloballyEnumeratedMessage>());

        // Assert
        Assert.IsInstanceOfType(actionResult, typeof(OkResult));
    }

在我返回422之前,我正在返回BadRequest,测试看起来像这样:

    [TestMethod]
    public void Post_InvalidGem_Returns400()
    {
        _gemPublisherMock.Setup(v => v.PublishGem(It.IsAny<GloballyEnumeratedMessage>())).Returns(ResultStatus.FromFailure());

        var controller = new PublishGemController(_gemPublisherMock.Object);

        // Act
        IHttpActionResult actionResult = controller.Post(It.IsAny<GloballyEnumeratedMessage>());

        // Assert
        Assert.IsInstanceOfType(actionResult, typeof(BadRequestResult));
    }

我想为另一个潜在的失败保留BadRequest,因此如果发布失败,则决定更改Post方法以返回422。我检查422状态代码的测试结果如何?

编辑:根据对问题的评论解决

[TestMethod]
public void Post_InvalidGem_Returns422()
{
    _gemPublisherMock.Setup(v => v.PublishGem(It.IsAny<GloballyEnumeratedMessage>())).Returns(ResultStatus.FromFailure());

    var controller = new PublishGemController(_gemPublisherMock.Object);

    // Act
    IHttpActionResult actionResult = controller.Post(It.IsAny<GloballyEnumeratedMessage>());
    var result = (StatusCodeResult) actionResult;

    // Assert
    Assert.IsInstanceOfType(actionResult, typeof(StatusCodeResult));
    Assert.AreEqual(422, (int)result.StatusCode);
}

1 个答案:

答案 0 :(得分:2)

以下控制器和测试执行我认为您想要完成的任务:

控制器:

public class MyTestController : ApiController
{
    [HttpPost]
    public IHttpActionResult Post([FromBody] object gem)
    {
        return new StatusCodeResult((HttpStatusCode)422, this);
    }
}

测试:

    [TestMethod]
    public void Post_Returns422()
    {
        var controller = new MyTestController();

        // Act
        IHttpActionResult actionResult = controller.Post(It.IsAny<object>());

        // Assert
        Assert.IsInstanceOfType(actionResult, typeof(StatusCodeResult));
        Assert.AreEqual((int)((StatusCodeResult)actionResult).StatusCode,422);
    }