EntityFramework-Reverse-POCO-Code-First-Generator icon indicating copy to clipboard operation
EntityFramework-Reverse-POCO-Code-First-Generator copied to clipboard

Using FakeDbContext with DI

Open MarkLFT opened this issue 3 years ago • 6 comments

Forgive me if I am being dim, but I can't seem to use the FakeDBContext with DI?

I am setting up the DI in my tests, and all my service classes use a repository, and that repository expects an IAppDBContext to be injected.

I have setup my Di for the repository and service classes, but I cannot find a way to use an instance of FakeAppDbContext with the services.AddDbContext() method;

I apologise if I am being dim here, but any help would be greatly appreciated.

MarkLFT avatar Nov 24 '21 06:11 MarkLFT

Hi Mark. I don't actually use DI in my unit tests. I new up the instance and pass it in to the thing being tested. Using DI container in unit tests

Here is an example (ignore the 'Repository' name, it can be anything that requires the DbContext) :

The unit test will usually fill in the FakeDBContext with happy path data, as well as another test that fills it with edge case data, and pass that into business logic/service being tested.

Incidentally if you did want to use DI, FakeDBContext inherits from the same interface (it must as its passed in to the sut) as your real DBContext so I would of thought it would be straight forward to do, however I've never done it like that in my unit tests.

sjh37 avatar Nov 24 '21 12:11 sjh37

Ok, many thanks for your advice. I don't think that will work well for me. I would need to pre-instantiate a dozen or so classes before I could use it. I think it will be easier for me to use an In-Memory provider and not use the Fake Context, which is a shame as I think that would have been far better.

Thanks anyway.

MarkLFT avatar Nov 25 '21 02:11 MarkLFT

With regards to inherit from the same interface, the issue seems to be around the fact the FakeDbContext inherits from the same IAppDbContext, but does not inherit from the base DbContext, and the AddDbContext does not like this.

Maybe I will have a play around with other options, I think it would be good if we could just use DI.

MarkLFT avatar Nov 25 '21 02:11 MarkLFT

Just to let you know, by getting FakeDbContext to inherit from DbContext, and setting up the service provider, I was able to use DI in my tests. The tests are so much neater easier now I don't have to instantiate so many classes in advance. So it can be done.

Thanks for a great product.

MarkLFT avatar Nov 25 '21 03:11 MarkLFT

Like this?

public class FakeMyDbContext : DbContext, IMyDbContext

Then change functions to use override ?

If you could provide me an example with an example unit test, I'd add this to the project and give you a free commercial licence.

sjh37 avatar Nov 25 '21 14:11 sjh37

I will put an example and unit test together for you. Will as soon as I finish the current tests I am writing.

MarkLFT avatar Nov 25 '21 15:11 MarkLFT