Testing Integration with .NET Core and NUnit

I have a controller that accepts a JWT claim, and if the requirement is true then I store the category Json string like this: -

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

      

This happens after the user logs on to my system and receives the bearer token.

I am trying to test this in an integration test like this: -

[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 looks like this: -

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

      

When I run the test, I get 401 (unauthorized) which is expected. How can I take this test? How can I submit a claim in a test to make sure it works?

Also, if I remove the [Authorize] filters, I still get 401 (unauthorized), which I think shouldn't happen.

Any help would be greatly appreciated!

thank

+3


source to share


1 answer


You can add a header Authorization

for every http client request:

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

      



This way, you don't need separate configurations for tests and a real environment.

+2


source







All Articles