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

Integration Testing with .NET Core and NUnit

我有一个正在接受 JWT 声明的控制器,如果声明正确,那么我将返回一个 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);
    }
}

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

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

[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 class如下:-

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");

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