简体   繁体   English

使用 NUnit 对 controller 操作进行单元测试

[英]Unit tests with NUnit for controller actions

I am building a REST API and have some controllers, that i would like to test.我正在构建一个 REST API 并有一些我想测试的控制器。 The problem is, for post methods, i need to mock the http request.问题是,对于发布方法,我需要模拟 http 请求。

My post method within the controller looks like this:我在 controller 中的 post 方法如下所示:

    [HttpPost]
    public async Task<IActionResult> Post([FromBody] xxx xxx)
    {
       ...

       return Ok(new Link()
       {
           Id = ...,
           Href = GetPath(id)
       });
   }


private string GetPath(int id)
    {
        var displayUrl = UriHelper.GetDisplayUrl(Request);
        var urlBuilder = new UriBuilder(displayUrl)
        {
            Query = null,
            Fragment = null
        };
        return urlBuilder.ToString() + "/" + id;
    }

As you can see inside the GetPath function there is Request.正如您在 GetPath function 中看到的,有请求。 This is always null and throws errors, when executing the unit test.这始终是 null 并在执行单元测试时引发错误。

My unit test so far (with mocked database):到目前为止我的单元测试(使用模拟数据库):

[Test]
    public async Task PostAsync_ReturnsHttpStatus200()
    {
        SaveObject object= new SaveObject
        {
            ...
        };

        var response = await controller.PostAsync(object);

        Assert.That(response, Is.InstanceOf(typeof(OkObjectResult)));
    }

I will not show the one time setup, as all the other parts of the unit test seem to work, only the previously explained problem does exist.我不会展示一次性设置,因为单元测试的所有其他部分似乎都可以工作,只有前面解释的问题确实存在。

How do i mock the request with ASP.Net Core (.Net Core 3.1)?如何使用 ASP.Net Core (.Net Core 3.1) 模拟请求?

In case anyone need, here is the solution that worked for OP.如果有人需要,这里是适用于 OP 的解决方案。
Set controller context and path before calling it inside test.在测试中调用它之前设置 controller 上下文和路径。

Controller.ControllerContext = new ControllerContext                                                
{
    HttpContext = new DefaultHttpContext()
};

Controller.ControllerContext.Request.Path = new PathString("/url");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM