Open MarkLFT opened 2 years ago
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.
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.
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.
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.
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.
I will put an example and unit test together for you. Will as soon as I finish the current tests I am writing.
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.