Hi Milan I think this is exactly how I would have approached this apart from one observation - really like the use of the Verify method when doing calls to other interfaces - try using Automock to setup mocks and then when you create your class use Automock Create method, the mocking will be done automatically using Dependency Injection - this helps when you grow out the class and add more dependencies saving you having to alter your previous tests. Great videos btw 😊
Hello Milan, I'm Brazilian and I've been following your content since the beginning and I think your teaching is very good. You don't think about creating a course or something?
Hi Milan, Your videos are very good. Can you share a video in which we can write unit test cases for repository classes, in this we will not hit to database but will execute CRUD functionality
Hi nice video, I am wondering what's that Result generic class, I'm just learning unit testing and didn't see that in the course I took, do you have a video explaining what is that?
Great job! Can the Command Validator be tested in the Handler unit test? When I call the endpoint, I can only try Command Validator in integration tests.
I wonder whether 100% code coverage with unit tests is even desireable. In simple cases like this one it is certainly possible without any trouble but if the code gets slightly more complex that can be a quite challenging goal, esp. if we consider path coverage. An alternative would be "risk based testing". What is your opinion?
But wouldn't you start writing the tests by first thinking about your handler signature? If you know you're going to write a handler and know its shape, you can deduce all test cases based on input (is the email valid, is it unique, do the first and last names need validation, what happens when they are not valid, etc.). So wouldn't you write your tests first, then write the handler in TDD fashion?
@@MilanJovanovicTech I’m new to software engineering but not programming. I’ve always done unit testing but not by writing tests, but by running the code to test the new feature, with different initial states. I think writing official tests is a good thing for commercial projects but I don’t do it for personal projects I work on solo at home.
Hello Milan. Thank you so much for the wonderful videos. I am learning so much from these. I have one small question. When the test if the email is Unique, is the unit test actually inserting this member into the database? And if yes, how can we prevent it?
Great coverage, pun intened! :) I do exactly the same so nothing to add much. I was wondering, do you know if VSIDE or other tools visualize coverage in actual source after the test run. I had this experience with vacode in golang and was a fantastic experience to see actual source highligthed after test run and immediatelly you’d see the unhighlighted-not tested code. Any idea? Also would love to see you cover that + calculating code coverage with eg coverlet. Good work Milan.
Thank you Milan. I have a question please, do we need to have seperate unit tests for the domain project? Or the domain project should be tested in the context of the Application project?
Hey Milan, I have one question. I see the IsFailure method of the Result class and can instantly recognize the pattern as my projects in work use a similar pattern for their code. I wanted to know if there was a framework that wrote all this boilerplate code (Result, IResult) class or are we creating all this code ourselves.
Nicely done! I am working on a project that doesn't use repository but context injected in the handler. How would you approach testing this? What is your opinion?
Personally I'm a fan of integrationtesting handlers using WebApplicationFactory and TestContainers to spin up a docker container with a SQL database. But if you prefer to unit test handlers and they have a direct dependency on DbContext, the go-to would be using InMemoryProvider for the DbContext to mock it that way. Just a side note that unit testing the handlers won't trigger any PipelineBehaviors for the full MediatR request, an integrationtest would.
As @pelfox suggested, in-memory EF provider is a very good option for unit testing EF context. I wouldn't advise mocking EF, you're going to end up going down a deep rabbit hole.
This was almost identical way to do CQRS handler unit testing what i end up to do some time ago. I like to know more UnitOfWork and how to approach repository implementation when Domain entity model is not 100% identical what database is using because legacy reasons. Specially how to deal entity id's when it's not GUID but database generated int?
This is an interesting topic really appreciate it. . .l would like us to get to how to launch 2 services that use docker in two containers but they use the same Application layer with just different entry points. . .which should be the benefit of the clean architecture, having multiple entry point and one code base, in two docker containers. . .one service could be the api and the other the outbox service for example.
@@MilanJovanovicTech Yes, multiple entry points l would call them for example. One container runs the api. One container runs a CLI. Both can create commands using the same code base but are started in different containers/services as they are different entry points to the application. This can be extended to N entry points/services using one code base.
Hi Milan, Great video, but I am missing one thing here, which is being able to mock the domain logic. Let's say I have a AcceptInvitationCommandHandler which gets a gathering from the repository and calls AcceptInvitation on it. I don't want to test the gathering's domain logic of the invitation being accepted and the attendee being added, I should have a separate domain unit test for that. However, I do want to validate the command handler has invoked AcceptInvitation properly. Do I have to create interfaces for every aggregate and have the repository return interfaces instead? Should my static factories return the interface aswell?
You shouldn't verify if it was invoked or not. You just need to verify the end result is what you expect it is. And test the Domain (AcceptInvitation in this case) in a separate test.
Hi Milan! What if I put repository setup into a different file and I want to add an entity to the list of the mocked repo and I wan to get this entity with a mocked get method? How could I give the parameters to the mocked get method, please? I thought I give them at the instantianation of the mocked repository or with a callback, I do not know.
The only issue being, what if I have another command sent from my command handler using the ISender / IMediator interface. That's a perfectly valid use of MediatR and CQRS, but how do you test it? Would that be a Unit Test technically if we don't mock the response from the other Command? Also, what if I actually want to test the entire flow together with the second Mediator command (even if that's called a Integration Test)?
Hey Milan. I was just about to start writing unit tests for a project so great timing 😀. A question though. why are you not validating the results of your value object creation, as they too can fail. Also, in a scenario like this where you create multiple value objects one after the other, how would you check the results? would you have an if statement after every one of them or is there a cleaner way you think? Thanks!
Fair point, I missed that kind of. But also video would be too long. I'll make a part 2! The idea is to add an extension method on Result, and validate all the results at the same time. We can return either first failure, or all failures.
I used ExecuteUpdateAsync method in one of my handle method, and it throws error during unit test. Is there any way we can test handler containing ExecuteUpdateAsync method.
What are you testing against to find the uniqueness of the email, a database? What is the state of of the database and how are you controlling it? Next time you run your test is will fail as you have already added the user to the db!
Hey Paul :) I'm not familiar with TDD approach, so I didn't go down that route. But I'll definitely use that for testing the Domain layer, that would be a great learning opportunity for me.
@@MilanJovanovicTech I have done it before, but unfortunately it is not currently applied in the company where I work for. The TDD culture still needs to be integrated here. However with this type of content I have the basis to continue practicing by myself. It would be interesting if you also make an integration testing video. Thanks for sharing Milan😃
Want to master Clean Architecture? Go here: bit.ly/3PupkOJ
Want to unlock Modular Monoliths? Go here: bit.ly/3SXlzSt
XUnit tests - check
Testing internal classes - check
Exactly what I was looking for. Thank you!!!
Awesome, glad I helped someone 😁😁
You can also write internals visible to with this shorthand:
Awesome, I didn't know that!
I didn't know about the internal visibility feature for test projects. Thanks Milan for your job.
You're welcome Sergio, glad you liked it 😁
yes Millan we need more unit testing videos. Thank you so much for such nice video.
I heard you loud and clear 😁
@@MilanJovanovicTech 😅
Hi Milan I think this is exactly how I would have approached this apart from one observation - really like the use of the Verify method when doing calls to other interfaces - try using Automock to setup mocks and then when you create your class use Automock Create method, the mocking will be done automatically using Dependency Injection - this helps when you grow out the class and add more dependencies saving you having to alter your previous tests. Great videos btw 😊
This is pretty cool! Growing list of dependencies is indeed a big pain. I have to explore Automock more now 😁
Great video! I don't code in C# anymore, switched to Kotlin, this video still give me some concept on what to do when unit testing CQRS related stuff.
Awesome, glad you liked it. I took a look at Kotlin once, and it seemed very similar to ASP .NET
You can use this csproj itemgroup item :
Pretty cool, I wasn't aware of that
Thank you, this will be very useful for my unit tests.
Awesome, Milica!
Hello Milan, I'm Brazilian and I've been following your content since the beginning and I think your teaching is very good. You don't think about creating a course or something?
Yes, I'm planning to release a course early next year :)
Hi Milan,
Your videos are very good.
Can you share a video in which we can write unit test cases for repository classes, in this we will not hit to database but will execute CRUD functionality
This could be helpful: th-cam.com/video/ikRPfoKl1SE/w-d-xo.html
also you could fill repository with predefined email and than the test will have purpose
Perhaps, but not what I tried to do in this video
Great job man! I'm learning a lot from your classes
Glad to hear it!
You did a great job Milan , it would be nice if we have a full series on testing
I'm surely going to make a few more videos!
Hi nice video, I am wondering what's that Result generic class, I'm just learning unit testing and didn't see that in the course I took, do you have a video explaining what is that?
This one here: th-cam.com/video/KgfzM0QWHrQ/w-d-xo.html
Hey man, thanks for the great video! I was wondering if you have a video/playlist where you are building the actualy application?
If you go back to the earliest videos, I start more or less from scratch
I love me some xunit + moq combination 👌
Awesome 🔥
Great job! Can the Command Validator be tested in the Handler unit test? When I call the endpoint, I can only try Command Validator in integration tests.
No, but check out my Testcontainers video which runs the entire MediatR pipeline.
Or you can unit test the command validator on its own.
I wonder whether 100% code coverage with unit tests is even desireable. In simple cases like this one it is certainly possible without any trouble but if the code gets slightly more complex that can be a quite challenging goal, esp. if we consider path coverage. An alternative would be "risk based testing". What is your opinion?
100% coverage should never be the goal by itself. The goal should be to write meaningful tests. And coverage will come on its own.
Please create more videos in your awesome Clean Architecture & DDD Series.
They're on the way!
But wouldn't you start writing the tests by first thinking about your handler signature? If you know you're going to write a handler and know its shape, you can deduce all test cases based on input (is the email valid, is it unique, do the first and last names need validation, what happens when they are not valid, etc.). So wouldn't you write your tests first, then write the handler in TDD fashion?
I don't practice TDD 🤷♂️ So it didn't make sense for me to start now. But I may try it for some video.
Hi! Thank's for the great content! What is Result class you use to wrap Guid? Ty
Something like this: gist.github.com/m-jovanovic/aa25b1ae424c985ff8ae696a79b6fe6e
Nice video Milan, thanks for good contents!
You're most welcome!
Very nice video ☺️
Will you ever make a video about integration tests?
At some point, definitely
Client: “why did the project take twice as long?”
Dev: “unit testing”
They'll thank you later when you don't need to do bug fixing
@@MilanJovanovicTech I’m new to software engineering but not programming. I’ve always done unit testing but not by writing tests, but by running the code to test the new feature, with different initial states.
I think writing official tests is a good thing for commercial projects but I don’t do it for personal projects I work on solo at home.
Hello Milan. Thank you so much for the wonderful videos. I am learning so much from these.
I have one small question. When the test if the email is Unique, is the unit test actually inserting this member into the database? And if yes, how can we prevent it?
No - these are just unit tests. They don't touch the DB.
Dam maaaaan, your left eyebrow move made me like your video, and right eyebrow move made me subscribe. Your are hypnotizer ot what?
Rofl 🤣 It's a super power of mine!
How to test actions which simply execute dapper (CQRS) queries?
Integration tests with Testcontainers
@@MilanJovanovicTechso actually testing against the database? Seed the database and assert against the expected results?
This was great! Thanks!
Awesome. What's your approach?
Great coverage, pun intened! :) I do exactly the same so nothing to add much. I was wondering, do you know if VSIDE or other tools visualize coverage in actual source after the test run. I had this experience with vacode in golang and was a fantastic experience to see actual source highligthed after test run and immediatelly you’d see the unhighlighted-not tested code. Any idea? Also would love to see you cover that + calculating code coverage with eg coverlet. Good work Milan.
I used dotCover for this, but it's a paid tool from Jetbrain. Well worth it to be honest.
Thank you very much sir
You are welcome
Thank you Milan.
I have a question please, do we need to have seperate unit tests for the domain project? Or the domain project should be tested in the context of the Application project?
Yes, for sure. For whatever reason I started from Application project 🤷♂️
I'll make sure to do a TDD style approach with Domain project soon.
You should have one unit test project per library you create. Integration tests can go through everything from the api endpoints.
Hey Milan, I have one question. I see the IsFailure method of the Result class and can instantly recognize the pattern as my projects in work use a similar pattern for their code.
I wanted to know if there was a framework that wrote all this boilerplate code (Result, IResult) class or are we creating all this code ourselves.
I wrote it myself, as it's not a lot of code. But there are a bunch of NuGet packages you can use: th-cam.com/video/C1oGnDEnS14/w-d-xo.html
Nicely done! I am working on a project that doesn't use repository but context injected in the handler. How would you approach testing this? What is your opinion?
Personally I'm a fan of integrationtesting handlers using WebApplicationFactory and TestContainers to spin up a docker container with a SQL database.
But if you prefer to unit test handlers and they have a direct dependency on DbContext, the go-to would be using InMemoryProvider for the DbContext to mock it that way.
Just a side note that unit testing the handlers won't trigger any PipelineBehaviors for the full MediatR request, an integrationtest would.
As @pelfox suggested, in-memory EF provider is a very good option for unit testing EF context. I wouldn't advise mocking EF, you're going to end up going down a deep rabbit hole.
Yeah. In memory done the job well actually. But was curious to hear your opinion! Thanks!
@@bojanpavlovic5038 I tried some sort of DbContext Mock once, but it really didn't scale. It requires a LOT of code to set up a test, not worth it.
I have made seed classes and a provider put all together and just load all in constructor. End up being very simple and easy
Good videos, but how can we test FluentValidation?
You can create a command and pass it to a validator instance for testing
This was almost identical way to do CQRS handler unit testing what i end up to do some time ago.
I like to know more UnitOfWork and how to approach repository implementation when Domain entity model is not 100% identical what database is using because legacy reasons. Specially how to deal entity id's when it's not GUID but database generated int?
Unit of Work video is coming out on Friday! 😁
And I'll tackle Entity Id generation in a separate video
This is an interesting topic really appreciate it. . .l would like us to get to how to launch 2 services that use docker in two containers but they use the same Application layer with just different entry points. . .which should be the benefit of the clean architecture, having multiple entry point and one code base, in two docker containers. . .one service could be the api and the other the outbox service for example.
Interesting idea. So basically two web apps, using the same projects underneath?
@@MilanJovanovicTech Yes, multiple entry points l would call them for example. One container runs the api. One container runs a CLI. Both can create commands using the same code base but are started in different containers/services as they are different entry points to the application. This can be extended to N entry points/services using one code base.
@@100kshooter5 Makes sense. I implemented something similar to that on my GitHub, check out the event-reminder repo
And I'll work on a video
@@MilanJovanovicTech Amazing thank you. . .
Hi Milan, What theme/colours are you using for the visual studio?
Hey! This is ReSharper dark theme
Hi Milan,
Great video, but I am missing one thing here, which is being able to mock the domain logic.
Let's say I have a AcceptInvitationCommandHandler which gets a gathering from the repository and calls AcceptInvitation on it.
I don't want to test the gathering's domain logic of the invitation being accepted and the attendee being added, I should have a separate domain unit test for that. However, I do want to validate the command handler has invoked AcceptInvitation properly.
Do I have to create interfaces for every aggregate and have the repository return interfaces instead? Should my static factories return the interface aswell?
You shouldn't verify if it was invoked or not. You just need to verify the end result is what you expect it is.
And test the Domain (AcceptInvitation in this case) in a separate test.
Hello Milan, Is there a repository where all the lessons you have done are collected?
At the moment, I only share the code with my Patreon supporters.
On occasion, I will post something on my GitHub also.
@@MilanJovanovicTech you can post all things
Hi Milan! What if I put repository setup into a different file and I want to add an entity to the list of the mocked repo and I wan to get this entity with a mocked get method? How could I give the parameters to the mocked get method, please? I thought I give them at the instantianation of the mocked repository or with a callback, I do not know.
With Moq, you can configure the Get method to return a list of your choosing
The only issue being, what if I have another command sent from my command handler using the ISender / IMediator interface. That's a perfectly valid use of MediatR and CQRS, but how do you test it? Would that be a Unit Test technically if we don't mock the response from the other Command? Also, what if I actually want to test the entire flow together with the second Mediator command (even if that's called a Integration Test)?
Testing the entire flow = write an integration test
Otherwise, you can mock the response and run with it
Hey Milan. I was just about to start writing unit tests for a project so great timing 😀. A question though. why are you not validating the results of your value object creation, as they too can fail. Also, in a scenario like this where you create multiple value objects one after the other, how would you check the results? would you have an if statement after every one of them or is there a cleaner way you think? Thanks!
Fair point, I missed that kind of. But also video would be too long. I'll make a part 2!
The idea is to add an extension method on Result, and validate all the results at the same time. We can return either first failure, or all failures.
And obviously VS2022 sets the project up with 99+ changes!
Hmm?
I used ExecuteUpdateAsync method in one of my handle method, and it throws error during unit test. Is there any way we can test handler containing ExecuteUpdateAsync method.
Use a proper DbContext
This is awesome!
Thank you!
excellent. Have you got github link for above example?
Yes, but only for me Patreon supporters
@@MilanJovanovicTech Patreon link please.
@@onedev7316 www.patreon.com/milanjovanovic
Why are you returning from repository Domain Entities and not Database Models? You set in the dbContext (UoW) Domains Entities. Why are you doing it?
Domain Entities are DB Entities also, that's why. I don't create separate models.
What are you testing against to find the uniqueness of the email, a database? What is the state of of the database and how are you controlling it? Next time you run your test is will fail as you have already added the user to the db!
We can always clear the DB before running the test
@@MilanJovanovicTech We can but we didn't, we didn't even mention the database.
@@TrOgaN_ Check out a few videos I've done on integration testing
@@MilanJovanovicTech This isn't integration testing, it's unit testing jtbc. i'm reluctant to look at any more videos sorry!
NSubstitute + Fluent Assertions + xUnit
How is NSubstitute compared to Moq?
@@MilanJovanovicTech For me personally better and easier API to work with.
Can you talk about docker
Yes!
@@MilanJovanovicTech It will be great if you talk about docker and how can we implemented in c#. Thank you
how can I get this repo?
Were you able to get access on Patreon?
Would have been nice to see more of a red, green, refactor approach apposed to you just intuitively knowing your initial test was not sound.
Hey Paul :) I'm not familiar with TDD approach, so I didn't go down that route. But I'll definitely use that for testing the Domain layer, that would be a great learning opportunity for me.
What if handler is void
Test if the mocks were called with correct values
Why not just put the Arrange lines in the constructor. In that way you want have all your duplicate code.
Good suggestion
Email should be ValueObject
Isn't it?
@@MilanJovanovicTech no it is just a string
Great video! Thank you Milan
Thanks, Fernando! How do you write unit tests?
@@MilanJovanovicTech I have done it before, but unfortunately it is not currently applied in the company where I work for. The TDD culture still needs to be integrated here. However with this type of content I have the basis to continue practicing by myself. It would be interesting if you also make an integration testing video. Thanks for sharing Milan😃
@@fernandocalmet Integration testing is definitely coming!
Have you had a chance to use/review FakeItEasy?
Only heard of it, never used it
Thanks for the video! Super helpful!
Glad you liked it :)