Unit testing ASP.NET Web API 2 Controller which returns custom result

╄→гoц情女王★ 提交于 2019-12-07 02:24:20

问题


I have a Web API 2 controller which has an action method like this:

public async Task<IHttpActionResult> Foo(int id)
{
    var foo = await _repository.GetFooAsync(id);
    return foo == null ? (IHttpActionResult)NotFound() : new CssResult(foo.Css);
}

Where CssResult is defined as:

public class CssResult : IHttpActionResult
{
    private readonly string _content;

    public CssResult(string content)
    {
        content.ShouldNotBe(null);
        _content = content;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(_content, Encoding.UTF8, "text/css")
        };

        return Task.FromResult(response);
    }
}

How do i write a unit test for this?

I tried this:

var response = await controller.Foo(id) as CssResult;

But i don't have access to the actual content, e.g i want to verify that the actual content of the response is the CSS i expect.

Any help please?

Is the solution to simply make the _content field public? (that feels dirty)


回答1:


Avoid casts, especially in unit tests. This should work:

var response = await controller.Foo(id);
var message = await response.ExecuteAsync(CancellationToken.None);
var content = await message.Content.ReadAsStringAsync();
Assert.AreEqual("expected CSS", content);


来源:https://stackoverflow.com/questions/30747775/unit-testing-asp-net-web-api-2-controller-which-returns-custom-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!