Force DbContext to throw Exception on SaveChanges() in unit test

c# ef-core-2.2 entity-framework-core unit-testing

Question

I´m using EF Core 2.2.0 with an InMemoryDatabase for testing. Is there a way to make it throw an exception when an operation is called, such as SaveChanges or Find?

I want to verify that a my business logic is handling the exception in a particular way. I know that I can abstract the DbContext all together, but with EF Core and the InMemoryDatabase I wish to access the DbContext directly without any more abstractions.

In my unit test I'm currently creating the DbContext as such:

var dbOptions = new DbContextOptionsBuilder<MyContext>()
        .UseInMemoryDatabase(Guid.NewGuid().ToString())
        .Options;
var context = new MyContext(dbOptions));

And my logic (extremely simplified):

public MyClass
{
    private MyContext _context;

    public MyClass(MyContext context)
    {
        _context = context;
    }

    public void SomeMethod()
    {

        try
        {
            */ .. Other stuff .. */
            var entity = context.Find(id);
            entity.SomeProperty = "Foo";
            context.SaveChanges();
        }
        catch(Exception e)
        {
            // I want to test this code...
            Log.Write("Something");
            DoSomethingElse();
        }
    }
}
1
0
1/16/2019 9:50:35 AM

Popular Answer

You could use my EntityFrameworkCoreMock library as a base, see https://github.com/huysentruitw/entity-framework-core-mock

and then override the behavior of the SaveChanges method like this:

dbContextMock.Setup(x => x.SaveChanges()).Callback(() => throw new Exception());
1
2/12/2019 8:57:55 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow