From d1ebb882e8484c80eca86cac80602fb4c1401834 Mon Sep 17 00:00:00 2001 From: 杨宇千 Date: Sun, 4 Aug 2019 21:30:53 +0800 Subject: Fix the database bug in unit tests. --- Timeline.Tests/Helpers/MyWebApplicationFactory.cs | 83 +++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Timeline.Tests/Helpers/MyWebApplicationFactory.cs (limited to 'Timeline.Tests/Helpers/MyWebApplicationFactory.cs') diff --git a/Timeline.Tests/Helpers/MyWebApplicationFactory.cs b/Timeline.Tests/Helpers/MyWebApplicationFactory.cs new file mode 100644 index 00000000..903cd670 --- /dev/null +++ b/Timeline.Tests/Helpers/MyWebApplicationFactory.cs @@ -0,0 +1,83 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Timeline.Models; +using Timeline.Services; +using Xunit.Abstractions; + +namespace Timeline.Tests.Helpers +{ + public class MyWebApplicationFactory : WebApplicationFactory where TStartup : class + { + // We should keep the connection, so the database is persisted but not recreate every time. + // See https://docs.microsoft.com/en-us/ef/core/miscellaneous/testing/sqlite#writing-tests . + private readonly SqliteConnection _databaseConnection; + + public MyWebApplicationFactory() : base() + { + _databaseConnection = new SqliteConnection("Data Source=:memory:;"); + _databaseConnection.Open(); + + InitDatabase(); + } + + private void InitDatabase() + { + var options = new DbContextOptionsBuilder() + .UseSqlite(_databaseConnection) + .Options; + + using (var context = new DatabaseContext(options)) + { + context.Database.EnsureCreated(); + context.Users.AddRange(TestMockUsers.MockUsers); + context.SaveChanges(); + } + } + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.ConfigureServices(services => + { + services.AddEntityFrameworkSqlite(); + services.AddDbContext(options => + { + options.UseSqlite(_databaseConnection); + }); + }) + .ConfigureTestServices(services => + { + services.AddSingleton(); + }); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _databaseConnection.Close(); + _databaseConnection.Dispose(); + } + + base.Dispose(disposing); + } + } + + public static class WebApplicationFactoryExtensions + { + public static WebApplicationFactory WithTestLogging(this WebApplicationFactory factory, ITestOutputHelper outputHelper) where TEntry : class + { + return factory.WithWebHostBuilder(builder => + { + builder.ConfigureLogging(logging => + { + logging.AddXunit(outputHelper); + }); + }); + } + } +} -- cgit v1.2.3