gpt4 book ai didi

c# - 尝试使用 UrlHelper 测试 Controller

转载 作者:行者123 更新时间:2023-11-30 14:45:21 27 4
gpt4 key购买 nike

尝试创建用于测试目的的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com