testing - 使用 .NET Core 和 NUnit 进行集成测试

标签 testing asp.net-core nunit integration-testing .net-core

我有一个接受 JWT 声明的 Controller ,如果声明正确,那么我将返回一个 Json 类别字符串,如下所示:-

[Authorize(Policy = "OnlyValidUsers")]
[Route("api/[controller]")]
public class CategoriesController : Controller
{
    private readonly IGenericService<Category> _categoriesService;

    public CategoriesController(IGenericService<Category> categoriesService)
    {
        _categoriesService = categoriesService;
    }

    [Authorize(Policy = "GenericUser")]
    [HttpGet("/api/Categories/Get", Name = "GetCategories")]
    public async Task<IActionResult> Get()
    {
        var categories = await _categoriesService.GetAll();
        return Json(categories);
    }
}

这发生在用户登录我的系统并获得不记名 token 之后。

我正尝试在集成测试中进行如下测试:-

[TestFixture]
public class CategoriesControllerIntegrationTests
{
    private HttpClient _client;
    private Category _testCategory;
    private string _request;

    [SetUp]
    public void Setup()
    {
        var basePath = PlatformServices.Default.Application.ApplicationBasePath;
        var projectPath = Path.GetFullPath(Path.Combine(basePath, "../../../../SportsStore.Tests"));

        var server = new TestServer(Utils.GetHostBuilder(new string[] { })
            .UseContentRoot(projectPath)
            .UseEnvironment("Development")
            .UseStartup<Startup>());

        _client = server.CreateClient();
        _testCategory = new Category
        {
            Name = Enums.GetEnumDescription(Enums.CategoryTestData.Name)
        };
        _request = Enums.GetEnumDescription(Enums.Requests.Categories);
    }

    [Test]
    public async Task Get_ReturnsAListOfCategories_CategoriesController()
    {
        var response = await _client.GetAsync(_request + "Get");
        response.EnsureSuccessStatusCode();

        Assert.IsTrue(true);
    }

Utils类如下:-

public class Utils
{
    public static IWebHostBuilder GetHostBuilder(string[] args)
    {
        var config = new ConfigurationBuilder()
                   .AddCommandLine(args)
                   .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                   .Build();

        return new WebHostBuilder()
            .UseConfiguration(config)
            .UseKestrel()
            .UseStartup<Startup>();
    }
}

当我运行测试时,我收到了预期的 401(未授权)。我怎样才能通过这个测试?我如何才能通过测试中的声明以验证其是否有效?

此外,如果我删除 [Authorize] 过滤器,我仍然会收到 401(未经授权),我认为这不应该发生。

任何帮助将不胜感激!

谢谢

最佳答案

您可以为http客户端的每个请求添加Authorization header :

_client = server.CreateClient();
_client .DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "VALID JWT goes here");

这样您就不需要为测试和真实环境单独配置。

关于testing - 使用 .NET Core 和 NUnit 进行集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43367389/

相关文章:

asp.net-core - ASP.NET Core 5 应用程序找不到 View 错误

docker - 如何在aspnet Nanoserver docker容器中安装Powershell Core?

asp.net-core - 当前上下文中不存在名称 "SqlServerValueGenerationStrategy"

c# - 如何从 TestContext 获取当前参数值?

ruby-on-rails - block 范围不一致之前的 Rspec

ruby-on-rails - rspec 测试 getter 和 setter 方法

unit-testing - 如何运行Nunit的显式测试用例

nunit - 使用 Nunit 计时问题进行 Watin 单元测试

testing - 使用 html 报告按顺序运行 Testcafe 测试

maven - 使用命令行更改 maven surefire reportsDirectory