Base solution for your next web application
Open Closed

AuthorizationProvider in unit test #948


User avatar
0
waku created

Hi,

I have an AuthorizationProvider, I injected the RoleManager into it, and in SetPermissions method, I used the RoleManager to grant some permissions to a role. The code is like this:

public class UserPermissionProvider : AuthorizationProvider
{
	private readonly RoleManager _roleManager;

	public UserPermissionProvider(RoleManager roleManager)
	{
		_roleManager = roleManager;
	}

	public override async void SetPermissions(IPermissionDefinitionContext context)
	{
		var somePermission = context.CreatePermission(...);
		
		var someRole = _roleManager.GetRoleByNameAsync("SomeRole").Result;
		_roleManager.GrantPermissionAsync(someRole, somePermission).Wait();
	}
}

Everything is fine, until unit tests.
I noticed that the SetPermission method is executed before seeding data code in my TestBase:

// SetPermission is executed event before the constructor method of TestBase!
protected XXXTestBase()
{
	//Seed initial data
	UsingDbContext(context => new InitialDataBuilder(context).Build());

	LoginAsDefaultTenantAdmin();
}

As a result, there's no data, no "SomeRole" in the database, so the SetPermission method failed.
How can I fix this problem?


1 Answer(s)