public GeneralTests(WebApplicationFactory <Startup> factory)
        {
            _factory = factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config.Sources.Clear();

                    config.SetBasePath(Directory.GetCurrentDirectory());
                    config.AddJsonFile("appSettings.json", optional: false, reloadOnChange: false);
                });
            });
        }
コード例 #2
0
            private HttpClient GetTestClient(IEventsRepository eventsRepository)
            {
                Program.ConfigureSetupLogging();
                HttpClient client = _factory.WithWebHostBuilder(builder =>
                {
                    builder.ConfigureTestServices(services =>
                    {
                        services.AddSingleton(eventsRepository);
                    });
                }).CreateClient();

                return(client);
            }
コード例 #3
0
 public StoreControllerV1ApiTests(WebApplicationFactory <Startup> factory, ITestOutputHelper output)
 {
     Factory           = factory;
     Output            = output;
     StoreServiceProxy = Substitute.For <IStoreServiceProxy>();
     HttpClient        = Factory.WithWebHostBuilder(builder =>
     {
         builder.ConfigureTestServices(services =>
         {
             services.AddSingleton(StoreServiceProxy);
         });
     }).CreateClient();
 }
コード例 #4
0
        public static WebApplicationFactory <T> WithAuthentication <T>(this WebApplicationFactory <T> factory, TestClaimsProvider claimsProvider) where T : class
        {
            return(factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(services =>
                {
                    services.AddAuthentication("Test")
                    .AddScheme <AuthenticationSchemeOptions, TestAuthHandler>("Test", op => { });

                    services.AddScoped <TestClaimsProvider>(_ => claimsProvider);
                });
            }));
        }
コード例 #5
0
        public void TestInitialize()
        {
            mock = new Mock <IBrouwerRepository>();
            var repository = mock.Object;
            var factory    = new WebApplicationFactory <BrouwerService.Startup>();

            client = factory.WithWebHostBuilder(builder =>
                                                builder.ConfigureTestServices(services =>
                                                                              services.AddScoped <IBrouwerRepository>(_ => repository))).CreateClient();
            brouwer1 = new Brouwer {
                Id = 1, Naam = "1", Postcode = 1000, Gemeente = "1"
            };
        }
コード例 #6
0
        public ApiServer(WebApplicationFactory <Startup> factory)
        {
            ClientFactory
            .Setup(_ => _.CreateClient(It.IsAny <string>()))
            .Returns(CreateWebServiceClient);

            Client = factory.WithWebHostBuilder(builder =>
                                                builder.ConfigureTestServices(services =>
                                                                              services.RemoveAll <IHttpClientFactory>().AddTransient(_ => ClientFactory.Object)
                                                                              )).CreateClient();

            Client.BaseAddress = new Uri("http://api.com/", UriKind.Absolute);
        }
コード例 #7
0
        public AvailabilityRequestValidationTests(WebApplicationFactory <Startup> factory)
        {
            var fakePilots = new Pilot();

            _client = factory.WithWebHostBuilder(builder =>
                                                 builder.ConfigureTestServices(services =>
            {
                // inject fake service dependency
                services.AddTransient <IRequestHandler <AvailabilityQuery, Pilot> >(implementationFactory =>
                                                                                    new FakeAvailabitlityQueryHandler(fakePilots));
            }))
                      .CreateClient();
        }
コード例 #8
0
        public StaffApiTests(WebApplicationFactory <Startup> factory)
        {
            _staffRepo = new Mock <IStaffRepository>();

            _factory = factory;
            _client  = _factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureServices(services =>
                {
                    services.AddSingleton <IStaffRepository>(_staffRepo.Object);
                });
            }).CreateClient();
        }
コード例 #9
0
        /// <summary>
        /// Initiates _client using passed appSettings
        /// </summary>
        /// <param name="appSettings">Overwrites configuration values, see API/appsetting.json</param>
        /// <param name="addServices"></param>
        public void InitiateClient(Dictionary <string, string> appSettings, Func <IServiceCollection, int> addServices)
        {
            Client = _factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(services => { addServices(services); });

                builder.ConfigureAppConfiguration((context, configBuilder) =>
                {
                    var c = configBuilder.AddInMemoryCollection(appSettings);
                });
            })
                     .CreateClient();
        }
コード例 #10
0
        public AnimalEndpointTests(WebApplicationFactory <Startup> webApplicationFactory)
        {
            //_webApplicationFactory = webApplicationFactory; //to use actual service (AnimalService) which is registered in Startup

            //to mock service:
            _webApplicationFactory = webApplicationFactory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureServices(services =>
                {
                    services.AddSingleton <IAnimalService, AnimalServiceMock>(); //you could use Moq here
                });
            });
        }
 public CustomMessageHandlerIntegrationTest(WebApplicationFactory <Startup> factory)
 {
     _factory = factory
                .WithWebHostBuilder(builder => builder.ConfigureTestServices(services =>
     {
         services.AddInlineValidator <HelloRequest>(rules =>
         {
             rules.RuleFor(r => r.Name).NotEmpty();
         });
         services.AddSingleton <IValidatorErrorMessageHandler>(new CustomMessageHandler());
         services.AddGrpcValidation();
     }));
 }
コード例 #12
0
        public TodowebIntegrationTest(WebApplicationFactory <Program> factory)
        {
            var projectDir = Directory.GetCurrentDirectory();
            var configPath = Path.Combine(projectDir, "appsettings.Test.json");

            this.factory_ = factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureAppConfiguration((context, conf) =>
                {
                    conf.AddJsonFile(configPath).Build();
                });
            });
        }
コード例 #13
0
        private HttpClient GetTestClientwithExternalclientMocked(HttpClient externalHttpClient)
        {
            var httpClientFactory = Mock.Of <IHttpClientFactory>(
                i => i.CreateClient(It.IsAny <string>()) == externalHttpClient);

            return(factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(services =>
                {
                    services.AddSingleton <IHttpClientFactory>(httpClientFactory);
                });
            }).CreateClient());
        }
        public static HttpClient SetupClient(this WebApplicationFactory <StartupTest> fixture)
        {
            var options = new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            };

            return(fixture.WithWebHostBuilder(
                       builder => builder
                       .UseStartup <StartupTest>()
                       .ConfigureTestServices(services => { })
                       ).CreateClient(options));
        }
        public async Task Get_ReturnsYourPayloadIfPayloadSignedWithValidJWTAuthentication()
        {
            var testSecretKey = "TestSecretKey";
            var client        = _factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureAppConfiguration((builderContext, config) =>
                {
                    config.AddInMemoryCollection(
                        new Dictionary <string, string>
                    {
                        { "JWT:DecodeSecret", testSecretKey },
                        { "JWT:HeaderName", _testHeaderName }
                    });
                });
            })
                                .CreateClient();

            var payload = new JObject()
            {
                { "itworks", true }
            };

            var token = JWT.Encode(payload, testSecretKey,
                                   JweAlgorithm.PBES2_HS256_A128KW, JweEncryption.A256CBC_HS512);

            client.DefaultRequestHeaders.Add(_testHeaderName, token);

            var response = await client.GetAsync("/echo");

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var responsePayload = JsonConvert.DeserializeObject <JObject>(
                await response.Content.ReadAsStringAsync());

            responsePayload
            .Should()
            .BeEquivalentTo(payload);
        }
コード例 #16
0
ファイル: ContactScenario.cs プロジェクト: wuangnguyen/crm
        public ContactScenario(WebApplicationFactory <Startup> factory)
        {
            var projectDir = Directory.GetCurrentDirectory();
            var configPath = Path.Combine(projectDir, "appsettings.json");

            _factory = factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureAppConfiguration((SourceContext, config) =>
                {
                    config.AddJsonFile(configPath);
                    config.AddEnvironmentVariables();
                });
            });
        }
コード例 #17
0
ファイル: TestRest.cs プロジェクト: ignatandrei/WebAPI2CLI
        private WebApplicationFactory <Startup> ConfigureServices(WebApplicationFactory <Startup> f)
        {
            var projectDir = Directory.GetCurrentDirectory();
            var configPath = Path.Combine(projectDir, $"appsettingsEnableCLI.json");

            return(f.WithWebHostBuilder(builder =>
            {
                //builder.ConfigureAppConfiguration((context, conf) =>
                //{
                //    conf.AddJsonFile(configPath);
                //});
                builder.UseSetting("CLI_ENABLED", "1");
            }));
        }
コード例 #18
0
        public HostStartupFixture(WebApplicationFactory <Startup> factory)
        {
            _factory = factory.WithWebHostBuilder(c => c.ConfigureTestServices(services =>
            {
                services.RemoveAll <ITaxasClient>();

                var taxasClientMock = new Mock <ITaxasClient>();
                taxasClientMock
                .Setup(obj => obj.GetTaxaJuros(It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult(0.01m));

                services.TryAddSingleton(taxasClientMock.Object);
            }));
        }
        public async Task GetCustomerAsync_CustomerExisted_ShouldReturnExpectedCustomer()
        {
            //Arrange
            //var client = _factory.CreateClient();

            //Переопределяем как угодно
            //_factory.WithWebHostBuilder((builder) => { }).CreateClient();

            //Переопределяем реальные зависимости заглушками
            var client = _factory.WithWebHostBuilder((builder) =>
            {
                builder.ConfigureTestServices(services =>
                {
                    services.AddScoped <INotificationGateway, FakeNotificationGateway>();
                });
            }).CreateClient();

            var expected = new CustomerResponse()
            {
                Id          = Guid.Parse("a6c8c6b1-4349-45b0-ab31-244740aaf0f0"),
                Email       = "*****@*****.**",
                FirstName   = "Иван",
                LastName    = "Петров",
                Preferences = new List <PreferenceResponse>()
                {
                    new PreferenceResponse()
                    {
                        Id   = Guid.Parse("ef7f299f-92d7-459f-896e-078ed53ef99c"),
                        Name = "Театр",
                    },
                    new PreferenceResponse()
                    {
                        Id   = Guid.Parse("76324c47-68d2-472d-abb8-33cfa8cc0c84"),
                        Name = "Дети",
                    }
                }
            };

            //Act
            var response = await client.GetAsync($"/api/v1/customers/{expected.Id}");

            //Assert
            response.IsSuccessStatusCode.Should().BeTrue();
            response.StatusCode.Should().Be(HttpStatusCode.OK);

            var actual = JsonConvert.DeserializeObject <CustomerResponse>(
                await response.Content.ReadAsStringAsync());

            actual.Should().BeEquivalentTo(expected);
        }
コード例 #20
0
 public StoriesControllerTests(WebApplicationFactory <Startup> factory)
 {
     _storyRepository = new TestStoryRepository();
     _client          = factory
                        .WithWebHostBuilder(builder =>
     {
         builder.ConfigureServices(services =>
         {
             services.AddSingleton(_storyRepository);
         });
         builder.UseEnvironment("test");
     })
                        .CreateClient();
 }
コード例 #21
0
        public void SetUp()
        {
            _mockMessageHandler = new Mock <HttpMessageHandler>();

            _factory = new WebApplicationFactory <Startup>();
            _client  = _factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureServices(services =>
                {
                    services.AddHttpClient("EnvironmentAgency")
                    .ConfigurePrimaryHttpMessageHandler(() => _mockMessageHandler.Object);
                });
            }).CreateClient();
        }
コード例 #22
0
        internal static HttpClient GetClientWithoutExceptionPage <T>(ApmAgent agent, WebApplicationFactory <T> factory) where T : class
        => factory
        .WithWebHostBuilder(n =>
        {
            n.Configure(app =>
            {
                app.UseElasticApm(agent, agent.Logger);

                RegisterRoutingAndMvc(app);
            });

            n.ConfigureServices(ConfigureServices);
        })
        .CreateClient();
コード例 #23
0
        protected virtual Task OneTimeSetup()
        {
            Client = _webAppFactory
                     .WithWebHostBuilder(builder =>
            {
                builder.ConfigureServices(ConfigureServices);
                builder.ConfigureTestServices(ConfigureTestServices);
            })
                     .CreateClient();

            Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            return(Task.CompletedTask);
        }
コード例 #24
0
        public DailyCountingControllerV1ApiTests(WebApplicationFactory <Startup> factory, ITestOutputHelper output)
        {
            Factory = factory;
            Output  = output;

            HttpsOnlyPredicate = Substitute.For <IHttpsOnlyPredicate>();
            HttpClient         = Factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(services =>
                {
                    services.AddSingleton(HttpsOnlyPredicate);
                });
            }).CreateClient();
        }
コード例 #25
0
        public static WebApplicationFactory <Startup> WithAuthentication <TAuthenticationHandler>(this WebApplicationFactory <Startup> factory) where TAuthenticationHandler : AuthenticationHandler <AuthenticationSchemeOptions>
        {
            return(factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(services =>
                {
                    services.RemoveAll(typeof(IUserInfoService));
                    services.AddScoped <IUserInfoService, UserInfoService>();

                    services.AddAuthentication("Test")
                    .AddScheme <AuthenticationSchemeOptions, TAuthenticationHandler>("Test", options => { });
                });
            }));
        }
コード例 #26
0
        public static HttpClient CreateClientWithTestAuth <T>(this WebApplicationFactory <T> factory, IEnumerable <Claim> claims) where T : class
        {
            var client = factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(services =>
                {
                    services.AddScoped <ITestClaimsProvider, TestClaimsProvider>(_ => new TestClaimsProvider(claims));
                });
            }).CreateClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(MockAuthenticationHandler.AuthenticationScheme);

            return(client);
        }
        public async Task InterestCompoundCalculateFuncionalTest_CorrectURLAsync()
        {
            var compoundApiHttpClient = compoundCalculatorApiFactory
                                        .WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(services =>
                {
                    services.AddTransient <IInterestRateService, InterestRateService>(provider =>
                                                                                      new InterestRateService(interestRateApiHttpClientMock.Object, validInterestRateApiConfigurationMock.Object));
                });
            })
                                        .CreateClient();

            var calculateCompoundResponse = await compoundApiHttpClient.GetAsync("calculajuros?valorinicial=100&meses=5");

            calculateCompoundResponse.EnsureSuccessStatusCode();

            var calculateResponseValue = await calculateCompoundResponse.Content.ReadAsStringAsync();

            var calculateValue = decimal.Parse(calculateResponseValue, new CultureInfo("pt-BR"));

            Assert.True(calculateValue > 0);
        }
コード例 #28
0
        public static WebApplicationFactory <TStartup> BuildApplicationFactory <TStartup>(this WebApplicationFactory <TStartup> factory) where TStartup : class
        {
            return(factory.WithWebHostBuilder(builder =>
            {
                builder.UseEnvironment("Testing");
                builder.ConfigureServices(services =>
                {
                    var sp = services.BuildServiceProvider();

                    using (var scope = sp.CreateScope())
                    {
                        var scopedServices = scope.ServiceProvider;
                        var db = scopedServices.GetRequiredService <AppDbContext>();
                        var logger = scopedServices
                                     .GetRequiredService <ILogger <WebApplicationFactory <TStartup> > >();

                        lock (_lock)
                        {
                            if (!_databaseInitialized)
                            {
                                db.Database.EnsureDeleted();
                                db.Database.EnsureCreated();

                                try
                                {
                                    Utilities.InitializeDbForTests(db);
                                    _databaseInitialized = true;
                                }
                                catch (Exception ex)
                                {
                                    logger.LogError(ex, "An error occurred seeding the " +
                                                    "database with test messages. Error: {Message}", ex.Message);
                                }
                            }
                        }
                    }
                });

                builder.ConfigureTestServices(services =>
                {
                    services.Configure <AppSettings>(myOptions =>
                    {
                        myOptions.Secret = JWTSecret;
                    });

                    // used to extend middleware pipeline with FakeRemoteIpAddressMiddleware
                    services.AddSingleton <IStartupFilter, CustomStartupFilter>();
                });
            }));
        }
コード例 #29
0
        public LoggingTest(WebApplicationFactory <Startup> factory)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .Enrich.FromLogContext()
                         .WriteTo.Providers(Program.Providers)
                         .CreateLogger();

            _factory = factory.WithWebHostBuilder(builder => builder
                                                  .UseSerilogTestLogging(options => options.FilterByNamespace(nameof(SampleWebApplicationSerilogAlternate))));
            //or
            //_factory = factory.WithWebHostBuilder(builder => builder
            //    .ConfigureLogging(logging => logging.AddSerilogTest(options => options.FilterByNamespace(nameof(SampleWebApplicationSerilogAlternate)))));
        }
コード例 #30
0
        public async Task TestSomeMoo()
        {
            using var client = _factory.WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(services =>
                {
                    services.AddSingleton <IRoomDataService, TestValuesService>();
                });
            }).CreateClient();

            var index = await client.GetStringAsync("/api/values");

            Assert.Equal("[\"value1\"]", index);
        }