尝试使用UrlHelper测试控制器 [英] Trying to Test a Controller with a UrlHelper

查看:58
本文介绍了尝试使用UrlHelper测试控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试创建用于测试目的的 URLHelper 会引发 NullReferenceException .

Trying to create a URLHelper for testing purposes throws a NullReferenceException.

示例:

[Fact]
public async void AuthenticateAsyncTest()
{
  // Arrange
  var controller = new Controller(serviceProvider)
  {
    Url = new UrlHelper(new ActionContext()) // Exception thrown
  };

  // Act
  var result = await controller.Authenticate() as ViewResult;

  // Assert
  Assert.NotNull(result);
}

每次运行此测试时,在 Url = new UrlHelper(new ActionContext())中引发的异常是:

Every time I run this Test, the Exception that is thrown in Url = new UrlHelper(new ActionContext()) is:

Exception.Message:

Exception.Message:

消息:System.NullReferenceException:对象引用未设置为对象的实例.

Message: System.NullReferenceException : Object reference not set to an instance of an object.

Exception.StackTrace:

Exception.StackTrace:

UrlHelperBase.ctor(ActionContext actionContext)ControllerUnitTest.AuthenticateAsyncTest()

UrlHelperBase.ctor(ActionContext actionContext) ControllerUnitTest.AuthenticateAsyncTest()

使用:

xUnit 2.4.1,Microsoft.NETCore.App 2.2.0,Microsoft.AspNetCore.Routing.Abstractions 2.2.0

xUnit 2.4.1, Microsoft.NETCore.App 2.2.0, Microsoft.AspNetCore.Routing.Abstractions 2.2.0

要重新创建异常:

  1. 创建一个空的MVC core 2.2解决方案
  2. 创建一个xunit测试项目
  3. 安装NuGet Microsoft.AspNetCore.Mvc.Core 2.2.0
  4. 在测试中编写:var Url = new UrlHelper(new ActionContext());
  5. 运行测试

应如下所示:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Xunit;

namespace XUnitTestProject1
{
    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            var Url = new UrlHelper(new ActionContext());
        }
    }
}

我的问题:

  1. 是否有错误,或者为什么这不起作用?
  2. 了解替代方法或链接的文献吗?

推荐答案

根据助手正在尝试访问原始示例中未提供的 actionContext.RouteData.Values .

The helper is trying to access actionContext.RouteData.Values which was not provided in the original example.

提供必要的依赖关系,以使测试顺利完成.

Provide the necessary dependencies for the test to flow to completion.

[Fact]
public async Task AuthenticateAsyncTest() {
    // Arrange
    var httpContext = new DefaultHttpContext();
    var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
    var controller = new Controller(serviceProvider) {
        Url = new UrlHelper(actionContext)
    };

    // Act
    var result = await controller.Authenticate() as ViewResult;

    // Assert
    Assert.NotNull(result);
}

还应避免对单元测试使用异步void.请改用 Task .

Also avoid using async void for unit tests. Use Task instead.

这篇关于尝试使用UrlHelper测试控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆