2

I come from a Java background, and in Java I used to write unit tests (although they were closer to integration tests) using an embedded, in memory database instance. I found tests like those much more useful than tests which include mocking, which may hide mistakes, and the mocking process is error prone itself. I also used things like embedded brokers, embedded NoSQL databases and so on, which did the work very well.

However, in the .Net ecosystem, I'm struggling to find a parallel. The docs only show the approach I do not like (and a rather basic one). Is there something like Mongo2Go (rare example of what I am looking for), but for relational databases? Is there a different approach I am missing?

1 Answer 1

2

Here are two options for testing the Entity Framework.

InMemory database is designed for tests that do not require strict relational database behavior.

[TestMethod]
public void Foo_DoesBar_WhenBaz()
{
    var options = new DbContextOptionsBuilder<BloggingContext>()
        .UseInMemoryDatabase(databaseName: "foo_bar_baz")
        .Options;

    using (var context = new BloggingContext(options))
    {
        ...
    }
}

SQLite in-memory mode is appropriate when tests require more relational behavior.

[TestMethod]
public void Foo_DoesBar_WhenBaz()
{
    var connection = new SqliteConnection("DataSource=:memory:");
    connection.Open();

    try
    {
        var options = new DbContextOptionsBuilder<BloggingContext>()
            .UseSqlite(connection)
            .Options;

        using (var context = new BloggingContext(options))
        {
            ...          
        }
    }
    finally
    {
        connection.Close();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, looks like it will do for now :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.