单元测试返回自定义结果的ASP.NET Web API 2 Controller

RPM*_*984 6 .net c# unit-testing asp.net-web-api asp.net-web-api2

我有一个Web API 2控制器,它有一个这样的动作方法:

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

在哪里CssResult定义为:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何为此编写单元测试?

我试过这个:

var response = await controller.Foo(id) as CssResult;
Run Code Online (Sandbox Code Playgroud)

但我无法访问实际内容,例如我想验证响应的实际内容是我期望的CSS.

有什么帮助吗?

解决方案是简单地将该_content领域公之于众吗?(感觉很脏)

And*_*tar 3

避免强制转换,尤其是在单元测试中。这应该有效:

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