Last active
January 3, 2020 21:51
-
-
Save ankitvijay/644a68a03b24520ab5d758dc2048ba78 to your computer and use it in GitHub Desktop.
Integration Tests - Approach 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TestStartup : IStartup { | |
private readonly string settings; | |
public TestStartup(string settings) { | |
this.settings = settings; | |
} | |
public void ConfigureServices(IServiceCollection services) { | |
var configuration = new ConfigurationBuilder() | |
.SetBasePath(Directory.GetCurrentDirectory()) | |
.AddJsonFile(settings, false) // Load appsettings.azure.json or appsettings.aws.json | |
.AddEnvironmentVariables() | |
.Build(); | |
services.AddMvc() | |
.SetCompatibilityVersion(version: CompatibilityVersion.Version_2_2); | |
//...Code to add required services based on configuration | |
} | |
public void Configure(IApplicationBuilder app) { | |
app.UseMvc(); | |
//...Code to configure test Startup | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TestServerFixture { | |
static readonly Dictionary<string, TestServer> cache = | |
new Dictionary<string, TestServer>(); | |
public TestServerFixture() { | |
//... | |
} | |
public HttpClient GetClient(string settings) { | |
TestServer server = null; | |
if(!cache.TryGetValue(settings, out server)) { | |
var startup = new TestStartup(settings); | |
var builder = new WebHostBuilder() | |
.ConfigureServices(services => { | |
services.AddSingleton<IStartup>(startup); | |
}); | |
server = new TestServer(builder); | |
cache.Add(settings, server); | |
} | |
return server.CreateClient(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyTest : IClassFixture<TestServerFixture> { | |
private readonly TestServerFixture fixture; | |
public MyTest(TestServerFixture fixture) { | |
this.fixture = fixture; | |
} | |
[Theory] | |
[InlineData("appsettings.aws.json")] | |
[InlineData("appsettings.azure.json")] | |
public async Task ShouldValidateTheGetApiResponse(string settings) { | |
var client = fixture.CreateClient(settings); | |
var result = await client.GetAsync("SOME_API_URL"); | |
// Code to Assert Result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment