小编Rha*_*eng的帖子

如何在 Asp.NetCore 控制器中模拟 HttpResponse?

我正在开发一个 Asp.NetCore 应用程序,其中一个控制器如下所示:

[HttpPost, Route("setCookies")]
public int SetCookies([FromBody] Dictionary<string, string> cookies)
{
    foreach (var cookie in cookies)
    {
        Response.Cookies.Append(cookie.Key, cookie.Value, new CookieOptions() { Path = "/", HttpOnly = true });
    }

    return 1;
}
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试为此控制器添加单元测试用例。

在我创建控制器的实例之后

var _controller = new Controller();
Run Code Online (Sandbox Code Playgroud)

并调用该方法

_controller.SetCookies(<some parameter>);
Run Code Online (Sandbox Code Playgroud)

它表明Responsenull

我检查了元数据,它显示这Response是抽象基类中的只读ControllerBase属性,如下所示:

public HttpResponse Response { get; }
Run Code Online (Sandbox Code Playgroud)

那么,有没有办法嘲笑这个Response财产呢?

c# unit-testing mocking asp.net-core

4
推荐指数
1
解决办法
1685
查看次数

标签 统计

asp.net-core ×1

c# ×1

mocking ×1

unit-testing ×1