Skip to content

Commit

Permalink
Adding IClassFixture to WebFixture<StartupStub> run only once when th…
Browse files Browse the repository at this point in the history
…e test class initializes

Changing protected to public

In AntiForgeryHelper adding a validation to check if the token is already created.
  • Loading branch information
mrodrigues1 committed Aug 8, 2018
1 parent 9d7278f commit 21c69bd
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 48 deletions.
8 changes: 4 additions & 4 deletions SimpleToDo.Web.IntegrationTest/Fixture/WebFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ public class WebFixture<TStartup> : Fixture, IDisposable where TStartup : class
{
private readonly IServiceProvider _services;

protected HttpClient Client;
public HttpClient Client;

protected ToDoDbContext DbContext { get; }
public ToDoDbContext DbContext { get; }

protected IDbContextTransaction Transaction;
public IDbContextTransaction Transaction;

public WebFixture()
{
var builder = WebHost.CreateDefaultBuilder()
IWebHostBuilder builder = WebHost.CreateDefaultBuilder()
.UseStartup<TStartup>();
var server = new TestServer(builder);
Client = server.CreateClient();
Expand Down
3 changes: 3 additions & 0 deletions SimpleToDo.Web.IntegrationTest/Helper/AntiForgeryHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ public static class AntiForgeryHelper

public static async Task<string> EnsureAntiforgeryTokenAsync(HttpClient client)
{
if (_antiforgeryToken != null)
return _antiforgeryToken;

var response = await client.GetAsync("/ToDoList/Create");
response.EnsureSuccessStatusCode();
if (response.Headers.TryGetValues("Set-Cookie", out IEnumerable<string> values))
Expand Down
18 changes: 12 additions & 6 deletions SimpleToDo.Web.IntegrationTest/Stub/StartupStub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SimpleToDo.Model.Entities;
using SimpleToDo.Repository.Contracts;
Expand All @@ -13,6 +14,13 @@ namespace SimpleToDo.Web.IntegrationTest.Stub
{
public class StartupStub
{
static StartupStub()
{
Configuration = GetConfiguration();
}

protected static IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
Expand All @@ -22,13 +30,8 @@ public void ConfigureServices(IServiceCollection services)
options.MinimumSameSitePolicy = SameSiteMode.None;
});


services.AddDbContext<ToDoDbContext>(
options =>
{
options.UseSqlServer(
"Server=(localdb)\\MSSQLLocalDB;Database=SimpleToDo;Trusted_Connection=True;MultipleActiveResultSets=true");
},
options => options.UseSqlServer(Configuration["DbConnection"]),
ServiceLifetime.Singleton,
ServiceLifetime.Singleton);

Expand Down Expand Up @@ -56,6 +59,9 @@ public void Configure(IApplicationBuilder app, ToDoDbContext dbContext)
template: "{controller=ToDoList}/{action=Index}/{id?}");
});
}

private static IConfiguration GetConfiguration()
=> new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
}

}
75 changes: 38 additions & 37 deletions SimpleToDo.Web.IntegrationTest/ToDoListControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,20 @@

namespace SimpleToDo.Web.IntegrationTest
{
public class ToDoListControllerTests : WebFixture<StartupStub>
public class ToDoListControllerTests : IClassFixture<WebFixture<StartupStub>>
{
[Fact]
public async Task Index_GetAsyncCall_ResponseReturnsSuccessStatusCode()
private readonly WebFixture<StartupStub> _fixture;

public ToDoListControllerTests(WebFixture<StartupStub> fixture)
{
//Arrange
var toDoList = ToDoListFactory.Create().Single();
toDoList.Name = "Integration Test";
await DbContext.ToDoList.AddAsync(toDoList);
await DbContext.SaveChangesAsync();
_fixture = fixture;
}

[Fact]
public async Task Index_GetAsyncCall_ResponseReturnsSuccessStatusCode()
{
//Act
var response = await Client.GetAsync("/");
var response = await _fixture.Client.GetAsync("/");

//Assert
response.EnsureSuccessStatusCode();
Expand All @@ -39,11 +40,11 @@ public async Task Index_GetAsyncCall_ReturnCreatedToDoListToView()
{
//Arrange
var toDoList = ToDoListFactory.Create().Single();
await DbContext.ToDoList.AddAsync(toDoList);
await DbContext.SaveChangesAsync();
await _fixture.DbContext.ToDoList.AddAsync(toDoList);
await _fixture.DbContext.SaveChangesAsync();

//Act
var response = await Client.GetAsync("/");
var response = await _fixture.Client.GetAsync("/");

//Assert
response
Expand All @@ -60,7 +61,7 @@ public async Task Create_GetAsyncCall_RetunOkStatusCode()
//Arrange

//Act
var response = await Client.GetAsync("/ToDoList/Create");
var response = await _fixture.Client.GetAsync("/ToDoList/Create");

//Assert
response
Expand All @@ -79,7 +80,7 @@ public async Task Create_PostAsyncCallWithValidToDoList_RedirectToIndexAction_Er
};

//Act
var response = await Client.PostAsync(
var response = await _fixture.Client.PostAsync(
"/ToDoList/Create",
new FormUrlEncodedContent(formData));

Expand All @@ -95,13 +96,13 @@ public async Task Create_PostAsyncCallWithValidToDoList_RedirectToIndexAction()
{
{
"__RequestVerificationToken",
await AntiForgeryHelper.EnsureAntiforgeryTokenAsync(Client)
await AntiForgeryHelper.EnsureAntiforgeryTokenAsync(_fixture.Client)
},
{ nameof(ToDoList.Name), "To Do List 1" }
};

//Act
var response = await Client.PostAsync(
var response = await _fixture.Client.PostAsync(
"/ToDoList/Create",
new FormUrlEncodedContent(formData));

Expand All @@ -114,11 +115,11 @@ public async Task Edit_GetAsyncCallWithNewToDoListId_ReturnToDoListToView()
{
//Arrange
var toDoList = ToDoListFactory.Create().Single();
await DbContext.ToDoList.AddAsync(toDoList);
await DbContext.SaveChangesAsync();
await _fixture.DbContext.ToDoList.AddAsync(toDoList);
await _fixture.DbContext.SaveChangesAsync();

//Act
var response = await Client.GetAsync($"/ToDoList/Edit/{toDoList.Id}");
var response = await _fixture.Client.GetAsync($"/ToDoList/Edit/{toDoList.Id}");

//Assert
response
Expand All @@ -135,7 +136,7 @@ public async Task Edit_GetAsyncCallWithNullId_ReturnNotFoundStatusCode()
//Arrange

//Act
var response = await Client.GetAsync("/ToDoList/Edit/");
var response = await _fixture.Client.GetAsync("/ToDoList/Edit/");

//Assert
response
Expand All @@ -149,22 +150,22 @@ public async Task Edit_PostAsyncCallWithValidIdAndToDoList_RedirectToIndexView()
{
//Arrange
var toDoList = ToDoListFactory.Create().Single();
await DbContext.ToDoList.AddAsync(toDoList);
await DbContext.SaveChangesAsync();
await _fixture.DbContext.ToDoList.AddAsync(toDoList);
await _fixture.DbContext.SaveChangesAsync();

var formData = new Dictionary<string, string>
{
{
"__RequestVerificationToken",
await AntiForgeryHelper.EnsureAntiforgeryTokenAsync(Client)
await AntiForgeryHelper.EnsureAntiforgeryTokenAsync(_fixture.Client)
},
{ "id", toDoList.Id.ToString() },
{ "Id", toDoList.Id.ToString() },
{ "Name", "ToDoList Test 1" }
};

//Act
var response = await Client
var response = await _fixture.Client
.PostAsync(
"/ToDoList/Edit/",
new FormUrlEncodedContent(formData));
Expand All @@ -178,21 +179,21 @@ public async Task Edit_PostAsyncCallWithModelStateInvalid_ReturnModelToEditView(
{
//Arrange
var toDoList = ToDoListFactory.Create().Single();
await DbContext.ToDoList.AddAsync(toDoList);
await DbContext.SaveChangesAsync();
await _fixture.DbContext.ToDoList.AddAsync(toDoList);
await _fixture.DbContext.SaveChangesAsync();

var formData = new Dictionary<string, string>
{
{
"__RequestVerificationToken",
await AntiForgeryHelper.EnsureAntiforgeryTokenAsync(Client)
await AntiForgeryHelper.EnsureAntiforgeryTokenAsync(_fixture.Client)
},
{ "id", toDoList.Id.ToString() },
{ "Id", toDoList.Id.ToString() }
};

//Act
var response = await Client
var response = await _fixture.Client
.PostAsync(
"/ToDoList/Edit/",
new FormUrlEncodedContent(formData));
Expand All @@ -211,25 +212,25 @@ public async Task Edit_PostAsyncCallWithConcurrency_ThrowDbConcurrencyException(
{
//Arrange
var toDoList = ToDoListFactory.Create().Single();
await DbContext.ToDoList.AddAsync(toDoList);
await DbContext.SaveChangesAsync();
await _fixture.DbContext.ToDoList.AddAsync(toDoList);
await _fixture.DbContext.SaveChangesAsync();

var toDoListDb = await DbContext.ToDoList.FirstOrDefaultAsync(x => x.Id == toDoList.Id);
var toDoListDb = await _fixture.DbContext.ToDoList.FirstOrDefaultAsync(x => x.Id == toDoList.Id);
toDoListDb.Name = "Concurrency";

var formData = new Dictionary<string, string>
{
{
"__RequestVerificationToken",
await AntiForgeryHelper.EnsureAntiforgeryTokenAsync(Client)
await AntiForgeryHelper.EnsureAntiforgeryTokenAsync(_fixture.Client)
},
{ "id", toDoList.Id.ToString() },
{ "Id", toDoList.Id.ToString() },
{ "Name", "ToDoList Test 1" }
};

//Act
Func<Task<HttpResponseMessage>> action = () => Client
Func<Task<HttpResponseMessage>> action = () => _fixture.Client
.PostAsync(
"/ToDoList/Edit/",
new FormUrlEncodedContent(formData));
Expand All @@ -245,20 +246,20 @@ public async Task DeleteConfirmed_PostAsyncCallWithValidIdAndToDoList_RedirectTo
{
//Arrange
var toDoList = ToDoListFactory.Create().Single();
await DbContext.ToDoList.AddAsync(toDoList);
await DbContext.SaveChangesAsync();
await _fixture.DbContext.ToDoList.AddAsync(toDoList);
await _fixture.DbContext.SaveChangesAsync();

var formData = new Dictionary<string, string>
{
{
"__RequestVerificationToken",
await AntiForgeryHelper.EnsureAntiforgeryTokenAsync(Client)
await AntiForgeryHelper.EnsureAntiforgeryTokenAsync(_fixture.Client)
},
{ "id", toDoList.Id.ToString() }
};

//Act
var response = await Client
var response = await _fixture.Client
.PostAsync(
$"/ToDoList/Delete/",
new FormUrlEncodedContent(formData));
Expand Down
2 changes: 1 addition & 1 deletion SimpleToDo/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public void ConfigureServices(IServiceCollection services)
services.AddTransient<ITaskRepository, TaskRepository>();

services.AddMemoryCache();
services.AddSession();
services.AddSession();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

Expand Down

0 comments on commit 21c69bd

Please sign in to comment.