Код: Выделить всё
/// IntegrationTest.cs
public class ClientTests : IClassFixture {
[Fact]
public async void Post_ShouldCreateClient()
{
var client = await CreateClientWithAuth(); // Here we create a user in the database
var content = JsonEncode( ... );
var user = await userManager.Users.ToListAsync(); // List with one user
Assert.Single( user ); // Pass: User exists
var result = await client.PostAsync( "/Api/Client", content ); // Fail: Database empty
}
Код: Выделить всё
/// Controller.cs
[HttpPost]
public async Task Create( [Bind]CreateClient model )
{
/// ...
var users = await _userManager.Users.ToListAsync(); // Empty list???
}
Код: Выделить всё
public class InvoicerApplicationFactory : WebApplicationFactory
{
private SqliteConnection? _connection;
protected override void ConfigureWebHost( IWebHostBuilder builder )
{
builder.ConfigureServices( services =>
{
services.RemoveAll();
services.RemoveAll();
// Create the connection to database
_connection = new SqliteConnection( "DataSource=:memory:" );
_connection.Open();
services.AddSingleton( container => _connection );
services.RemoveAll();
services.AddDbContext( ( container, options ) =>
{
options.UseSqlite( _connection );
} );
// Migrate the database
var sp = services.BuildServiceProvider();
var scope = sp.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
db.Database.EnsureCreated();
} );
builder.UseEnvironment( "Testing" );
}
protected override void Dispose( bool disposing )
{
base.Dispose( disposing );
_connection?.Dispose();
}
}
< pre class="lang-cs Prettyprint-override">
Код: Выделить всё
protected async Task CreateClientWithAuth( string email = "admin@test.com", string password = "admin" )
{
return CreateClientWithAuth( await CreateUser( email, password ) );
}
protected HttpClient CreateClientWithAuth( User authenticatedUser )
{
this.authenticatedUser = authenticatedUser;
var client = factory.WithWebHostBuilder( builder =>
{
builder.ConfigureTestServices( services =>
{
services.AddAuthentication( defaultScheme: "TestScheme" )
.AddScheme(
"TestScheme", options => {
options.DefaultUser = authenticatedUser;
} );
} );
} )
.CreateClient();
return client;
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... controller
Мобильная версия