C
C#•7mo ago
skmkqw

Is my unit testing approach correct?

Hello everybody, i'm getting into backend development in asp.net core and ef. i've already built a simple API, but it has an overkill architecure (made this in educational purposes). Now I'm trying to cover the whole project in unit tests. Since I use dbContext -> repository -> service -> controller pattern, i came up with an idea on how to test it: while testing the controller, i will create a mock service, while testing the service, i will create a mock repository, while testing the repository, I will create a fixture database with an example dataset. Does this make sense? You can see my latest code here https://github.com/skmkqw/ProjectManagementAPI at "unitTests" branch. I also hear of something called FluentAssertions. Should i user it from the beggining or should i introduce it later when I will get used to writing tests in regular xUnit?
GitHub
GitHub - skmkqw/ProjectManagementAPI
Contribute to skmkqw/ProjectManagementAPI development by creating an account on GitHub.
7 Replies
Pobiega
Pobiega•7mo ago
first things first, please add a .gitignore to your project root you can create one with good default values by doing dotnet new gitignore Your overall idea is what a lot of people do when they hear about unitesting. Mock everything that isnt your service under test and go nuts. The result is a lot of tests that give little actual value I'm afraid, and you'll end up primarily testing your mocks A more realistic approach is to not use unittests for these things, and use integration tests instead. That means that you would write a test that starts by hitting your controller and executes the real actual code all the way down to the database and back up. You can then verify that the correct things were returned AND saved to the database.
skmkqw
skmkqwOP•7mo ago
Thanks. As i can understand, units will be suitable for projects with more businness logic, when mine is very simple, so i just need to be sure that my data flow is ok
Pobiega
Pobiega•7mo ago
its not as easy to get started with, but integration tests give you much more accurate tests that cover a much larger portion of your codebase, and more accurately reflects your true application. Pretty much. Where unit tests are the very best is pure functions or other "utility" style methods
skmkqw
skmkqwOP•7mo ago
thanks. i'll look through my code again, and then start learning integrational tests
Pobiega
Pobiega•7mo ago
There are some tools that really help with proper integration tests. My personal favorites are TestContainers and Respawn
skmkqw
skmkqwOP•7mo ago
thanks
Pobiega
Pobiega•7mo ago
Regarding FluentAssertions, the only thing it does is replace your Assert.Equals(expected, actual); calls with actual.Should().Be(expected); and give you much better error messages when they fail 🙂 I recommend starting with it asap
Want results from more Discord servers?
Add your server