public async Task AddSingleUserToSingleRole() { var testContextBuilder = TestContextBuilder.CreateDefault(builder => builder .AddDatabase() .SeedDefaults() .SeedDataset(Datasets.Dataset1)); await using var testContext = await testContextBuilder.BuildAsync(); var command = new AddUsersToRolesCommand { UserNames = new[] { "JohnDoe", }, RoleNames = new[] { nameof(RoleEnum.Administators) }, }; var commandContext = new CommandContext(command, testContext.Services); var handler = ActivatorUtilities.CreateInstance <AddUsersToRolesCommandHandler>(testContext.Services); await handler.HandleAsync(command, commandContext, default); await using (var dbContext = testContext.CreateReadOnlyDbContext()) { var user = await dbContext.Users .Include(user => user.Roles).ThenInclude(userRole => userRole.Role) .FirstAsync(user => user.UserName == command.UserNames[0]); Assert.Equal(1, user.Roles?.Count); Assert.Contains(user.Roles, userRole => userRole.Role.RoleName == command.RoleNames[0]); } }
public async Task <IActionResult> AddUsersToRoles([FromBody] AddUsersToRolesCommand model) { if (model == null) { return(BadRequest()); } await _commandDispatcher.DispatchAsync(model, HttpContext.RequestAborted); return(Ok()); }
public async Task CommandDataAnnotationsValidatorInterceptorTest() { var testContextBuilder = TestContextBuilder.CreateDefault(builder => builder .AddServices(services => { services.AddSingleton <IHostApplicationLifetime>(NullHostApplicationLifetime.Instance); services.AddServiceLayer(new OptionsProvider(builder.CreateDataAccessOptions())); }) .AddDatabase(addDataAccessServices: false)); await using var testContext = await testContextBuilder.BuildAsync(); var command = new AddUsersToRolesCommand { UserNames = new string[] { }, RoleNames = new string[] { "x" } }; var commandDispatcher = testContext.Services.GetRequiredService <ICommandDispatcher>(); var ex = await Assert.ThrowsAsync <ServiceErrorException>( async() => await commandDispatcher.DispatchAsync(command, default)); Assert.Equal(ServiceErrorCode.ParamNotValid, ex.ErrorCode); Assert.Equal(new[] { nameof(command.UserNames) }, ex.Args); }