Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dependency injection in a unit test class

I am using xunit to write unit tests for my web api. My web api uses dependency injection to pass along a DbContext and an IConfiguration as parameters using constructor injection. I would like to be able to do this in my unit tests project so that I can easily have access to the DbContext and IConfiguration. I have read about using a fixture to do this but I have not found a good example on how this would be handled. I have seen articles using the TestServer class but my project targets the .NETCoreApp1.1 framework which won't let me use the TestServer class. Any suggestions here?

like image 750
sabo Avatar asked May 05 '26 09:05

sabo


1 Answers

Are you sure that you need to use those dependencies in your tests? According to unit testing philosophy consider using some mock frameworks to provide dummy instances of your DbContext and IConfiguration with suitable behavior and values. Try to look into NSubstitute or Moq framework.

like image 106
Yevhen Krupin Avatar answered May 07 '26 22:05

Yevhen Krupin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!