Faking authorization and injecting services #855
-
I'm still new to Blazor and bUnit, so still learning my way around. I'm running into an issue with injecting services and faking authorization. In this example I will be using DevExpress, but it can be any service, I always get a Edit: If I remove the authorization requirements on the razor page and run the test without faking the authorization, the test renders fine. This is Blazor WASM if that matters. @page "/"
<PageTitle>Home</PageTitle>
<AuthorizeView>
<Authorized>
<div class="col-6 d-flex justify-content-end pe-0">
<DxButton RenderStyle="ButtonRenderStyle.Primary" RenderStyleMode="ButtonRenderStyleMode.Contained"
Text="Click Me!" />
</div>
</Authorized>
<NotAuthorized>
Not Authorized
</NotAuthorized>
</AuthorizeView> using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using App_ConsoleDx.Features;
using Bunit;
using Microsoft.Extensions.DependencyInjection;
using DevExpress.Blazor;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.JSInterop;
using Xunit;
using Microsoft.AspNetCore.Components.Authorization;
using App_ConsoleDx.Features.Users;
namespace Test_ConsoleDx
{
public class Home_Test : TestContext
{
[Fact]
public void Test1()
{
Services.AddDevExpressBlazor();
Services.AddAuthorizationCore();
using var ctx = new TestContext();
var authContext = ctx.AddTestAuthorization();
authContext.SetAuthorized("TEST USER");
var cut = ctx.RenderComponent<CascadingAuthenticationState>(x => x.AddChildContent<Home>());
var a = cut.Find("button").TextContent;
Console.WriteLine("a is : " + a);
Assert.Equal("Click Me!", a);
}
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You should only do one of those:
When you inherit it, your test class becomes a Your problem is likely that you are adding your services to your test classes I also suspect you don't need the AddAuthorizationCore call. Hope this helps. |
Beta Was this translation helpful? Give feedback.
Hi @friedice5467
You should only do one of those:
TestContext
TestContext
up in your testWhen you inherit it, your test class becomes a
TestContext
, and you do not need to new it up.Your problem is likely that you are adding your services to your test classes
Services
collection but using theTestContext
you new up to render your components, which means the services are missing from it and thus not available to your components.I also suspect you don't need the AddAuthorizationCore call.
Hope this helps.