Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setup Subcutaneous testing with SqlServer #35

Open
NathanTe opened this issue Apr 24, 2024 · 0 comments
Open

Setup Subcutaneous testing with SqlServer #35

NathanTe opened this issue Apr 24, 2024 · 0 comments

Comments

@NathanTe
Copy link

Hey,

First of all amazing template, I build a financial app with ease.

Now I'm getting around to writing my tests 馃槥.

I see you used Sqlite for you test db in your integration tests.
I would like to use an SqlServer test db but can't seem to get it to work.

Error: Microsoft.Data.SqlClient.SqlException : Cannot open database "Testing" requested by the login. The login failed.

Tried:

  • creating the database 'Testing' in advance using SSMS.
  • removing the ensureDeleted();

The code based on your template is below.
Hopefully one you guys can help me further 馃槂.

Thanks in advance,
Nathan

// WebAppFactory
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
    TestDatabase = SqlServerTestDatabase.CreateAndInitialize();

    builder.ConfigureTestServices(services =>
    {
        services
            .RemoveAll<DbContextOptions<AppDbContext>>()
            .AddDbContext<AppDbContext>((sp, options) => options.UseSqlServer(TestDatabase.Connection));
    });

// SqlServerTestDatabase
public class SqlServerTestDatabase : IDisposable
{
    public SqlConnection Connection { get; }

    public static SqlServerTestDatabase CreateAndInitialize()
    {
        var testDatabase = new SqlServerTestDatabase("Server=localhost;Database=Testing;Trusted_Connection=True;TrustServerCertificate=true;");

        testDatabase.InitializeDatabase();

        return testDatabase;
    }

    public void InitializeDatabase()
    {
        Connection.Open();
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseSqlServer(Connection)
            .Options;

        using var context = new AppDbContext(options, null!);
        context.Database.EnsureDeleted();
        context.Database.EnsureCreated();
    }

    public void ResetDatabase()
    {
        Connection.Close();

        InitializeDatabase();
    }

    public void Dispose()
    {
        Connection.Close();
    }

    private SqlServerTestDatabase(string connectionString)
    {
        Connection = new SqlConnection(connectionString);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant