c# - 尝试使用 UrlHelper 测试 Controller

标签 c# unit-testing xunit asp.net-core-mvc-2.0

尝试创建用于测试目的的 URLHelper 会引发 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()) 中抛出的异常是:

异常.消息:

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

异常.StackTrace:

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

使用:

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

重新创建异常:

  1. 创建一个空的 MVC 核心 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. 解决方法的文献或链接是否受到赞赏?

最佳答案

根据 GitHub source code由异常消息引用,

protected UrlHelperBase(ActionContext actionContext)
{
    if (actionContext == null)
    {
        throw new ArgumentNullException(nameof(actionContext));
    }

    ActionContext = actionContext;
    AmbientValues = actionContext.RouteData.Values;
    _routeValueDictionary = new RouteValueDictionary();
}

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

为测试提供必要的依赖关系以完成。

[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);
}

同时避免在单元测试中使用 async void。请改用 Task

关于c# - 尝试使用 UrlHelper 测试 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54199103/

相关文章:

c# - 从 C# Windows 应用程序创建 .exe

c# - 为什么 'public event EventHandler cccc' 为空?

python - 值错误 : no such test method in <class 'myapp.tests.SessionTestCase' >: runTest

java - Play 框架 - 具有依赖关系的单元测试 Controller

c# - 这种 Assert.AreSame 应该返回 true 吗?

c# - 如何模拟 Entity Framework 的 FromSqlRaw 方法?

c# - IAuthenticationFilter 中的 ActionContext.ActionArguments 为空

c# - 正则表达式中的问题

c# - 使用 Assert.AreEqual() 比较两个对象

c# - 模拟 HttpContext.Current.User.Identity.Name