33// See the LICENSE file in the project root for more information.
44// Maintainer: Argo Zhang(argo@live.ca) Website: https://www.blazor.zone
55
6+ using Microsoft . AspNetCore . Components . Authorization ;
67using Microsoft . Extensions . Options ;
78using Microsoft . JSInterop ;
9+ using System . Security . Claims ;
810
911namespace UnitTest . Services ;
1012
@@ -17,6 +19,9 @@ public async Task Callback_Ok()
1719 context . JSInterop . Mode = JSRuntimeMode . Loose ;
1820 context . Services . AddBootstrapBlazor ( ) ;
1921
22+ var authorizationContext = new MockAuthenticationStateProvider ( ) ;
23+ context . Services . AddScoped < AuthenticationStateProvider > ( p => authorizationContext ) ;
24+
2025 var options = context . Services . GetRequiredService < IOptions < BootstrapBlazorOptions > > ( ) ;
2126 options . Value . ConnectionHubOptions = new ( )
2227 {
@@ -36,6 +41,7 @@ await cut.InvokeAsync(async () =>
3641 await Task . Delay ( 100 ) ;
3742 client . SetData ( new ClientInfo ( ) { Id = "test_id" , Ip = "::1" } ) ;
3843 } ) ;
44+
3945 await cut . Instance . Callback ( new ClientInfo { Id = "test_id" , Ip = "::1" } ) ;
4046 } ) ;
4147 Assert . Equal ( 1 , service . Count ) ;
@@ -49,12 +55,15 @@ await cut.InvokeAsync(async () =>
4955
5056 // 触发 Beat 时间
5157 await Task . Delay ( 200 ) ;
58+ authorizationContext . SetAuthorized ( "mock_user" ) ;
5259 await cut . InvokeAsync ( async ( ) =>
5360 {
5461 await cut . Instance . Callback ( new ClientInfo { Id = "test_id" , Ip = "::1" } ) ;
5562 } ) ;
5663 Assert . True ( service . TryGetValue ( "test_id" , out var item ) ) ;
5764 Assert . NotNull ( item ? . ClientInfo ) ;
65+ Assert . Equal ( "mock_user" , item . ClientInfo . UserName ) ;
66+
5867 Assert . True ( item ? . ConnectionTime < DateTimeOffset . Now ) ;
5968 cut . Dispose ( ) ;
6069
@@ -155,4 +164,24 @@ public void ConnectionService_Ok()
155164 var d = service as IDisposable ;
156165 d ? . Dispose ( ) ;
157166 }
167+
168+ class MockAuthenticationStateProvider : AuthenticationStateProvider
169+ {
170+ ClaimsPrincipal _claim = new ( ) ;
171+ public override async Task < AuthenticationState > GetAuthenticationStateAsync ( )
172+ {
173+ await Task . Yield ( ) ;
174+
175+ var state = new AuthenticationState ( _claim ) ;
176+ return state ;
177+ }
178+
179+ public void SetAuthorized ( string userName )
180+ {
181+ _claim = new ClaimsPrincipal ( new ClaimsIdentity ( new Claim [ ]
182+ {
183+ new ( ClaimTypes . Name , userName ) ,
184+ } , "mock" ) ) ;
185+ }
186+ }
158187}
0 commit comments