mardi 5 novembre 2019

Why my WebApplicationFactory using diffrent database?

I added an user and when i get a list of users it actually exists but when i tried to get token i can't get it becouse that user doesn't exists. I'am sure that login and password are correct so i should recieve a token but i have error "invalid grant".

        public AccountAdminTest(ITestOutputHelper output)
        {
            this.output = output;

            _factory = new CustomWebApplicationFactory<Startup>();

            _client = _factory.CreateClient(new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = true,
                BaseAddress = new Uri("https://localhost:44444")
            });

            scopeFactory = _factory.Services.GetService<IServiceScopeFactory>();
            _scope = scopeFactory.CreateScope();
            _context = _scope.ServiceProvider.GetService<ApplicationDbContext>();

            var _user = User.getAppAdmin();
            _context.Add(_user);
            _context.SaveChanges();

            var userList = _context.Users.ToList();

            tokenGetter = new TokenGetter(_client);
            var _token = tokenGetter.GetAccessToken(_user.Email, "Ziemia123$", "velox_swagger_ui", IdentityServerConstants.LocalApi.ScopeName).Result;

            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);

        }
    public class CustomWebApplicationFactory<TStartup>
     : WebApplicationFactory<TStartup> where TStartup : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureTestServices(services =>
            {
                var descriptor = services.SingleOrDefault(
                d => d.ServiceType ==
                    typeof(DbContextOptions<ApplicationDbContext>));

                if (descriptor != null)
                {
                    services.Remove(descriptor);
                }

                services.RemoveAll(typeof(ApplicationDbContext));

                services.AddDbContext<ApplicationDbContext>((options, context) =>
                {
                    context.UseInMemoryDatabase($"{Guid.NewGuid()}");
                });
            });
        }
    }

Aucun commentaire:

Enregistrer un commentaire