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();
}
}
}
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());