簡體   English   中英

單元測試返回自定義結果的ASP.NET Web API 2 Controller

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

我有一個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);
}

其中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);
    }
}

我如何為此編寫單元測試?

我試過這個:

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

但我無法訪問實際內容,例如,我想驗證響應的實際內容是我期望的CSS。

有什么幫助嗎?

解決方案是簡單地將_content字段公開嗎? (感覺很臟)

避免使用石膏,特別是在單元測試中。 這應該工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM