Unit Testing CQRS Handlers With Moq, Fluent Assertions, and xUnit

  Рет қаралды 37,383

Milan Jovanović

Milan Jovanović

Күн бұрын

Пікірлер: 137
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Want to master Clean Architecture? Go here: bit.ly/3PupkOJ Want to unlock Modular Monoliths? Go here: bit.ly/3SXlzSt
@kinggrizzly13
@kinggrizzly13 Жыл бұрын
XUnit tests - check Testing internal classes - check Exactly what I was looking for. Thank you!!!
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Awesome, glad I helped someone 😁😁
@sergiom.954
@sergiom.954 Жыл бұрын
I didn't know about the internal visibility feature for test projects. Thanks Milan for your job.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
You're welcome Sergio, glad you liked it 😁
@SajidAliSoftwareEngineer
@SajidAliSoftwareEngineer Жыл бұрын
yes Millan we need more unit testing videos. Thank you so much for such nice video.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
I heard you loud and clear 😁
@SajidAliSoftwareEngineer
@SajidAliSoftwareEngineer Жыл бұрын
@@MilanJovanovicTech 😅
@MarcusKaseder
@MarcusKaseder Жыл бұрын
You can also write internals visible to with this shorthand:
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Awesome, I didn't know that!
@martinbryant3515
@martinbryant3515 Жыл бұрын
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 😊
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
This is pretty cool! Growing list of dependencies is indeed a big pain. I have to explore Automock more now 😁
@BEARMC27
@BEARMC27 Жыл бұрын
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.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Awesome, glad you liked it. I took a look at Kotlin once, and it seemed very similar to ASP .NET
@jogadordejogos4041
@jogadordejogos4041 Жыл бұрын
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?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Yes, I'm planning to release a course early next year :)
@milicabozic9897
@milicabozic9897 Жыл бұрын
Thank you, this will be very useful for my unit tests.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Awesome, Milica!
@calblui
@calblui Жыл бұрын
Great job man! I'm learning a lot from your classes
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Glad to hear it!
@ibrahimhebish1404
@ibrahimhebish1404 Жыл бұрын
You did a great job Milan , it would be nice if we have a full series on testing
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
I'm surely going to make a few more videos!
@hamitkarahan2973
@hamitkarahan2973 Жыл бұрын
Nice video Milan, thanks for good contents!
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
You're most welcome!
@woquendoG
@woquendoG Жыл бұрын
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?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
This one here: kzbin.info/www/bejne/gZjJq4Bmhrx7qLM
@Yash42189
@Yash42189 Жыл бұрын
Hey man, thanks for the great video! I was wondering if you have a video/playlist where you are building the actualy application?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
If you go back to the earliest videos, I start more or less from scratch
@ajaypanse4489
@ajaypanse4489 8 ай бұрын
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
@MilanJovanovicTech
@MilanJovanovicTech 8 ай бұрын
This could be helpful: kzbin.info/www/bejne/n5y1gZmlgNFkiac
@EHBRod13
@EHBRod13 Жыл бұрын
Thanks for the video! Super helpful!
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Glad you liked it :)
@alexalexander3252
@alexalexander3252 Жыл бұрын
Dam maaaaan, your left eyebrow move made me like your video, and right eyebrow move made me subscribe. Your are hypnotizer ot what?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Rofl 🤣 It's a super power of mine!
@vekzdran
@vekzdran Жыл бұрын
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.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
I used dotCover for this, but it's a paid tool from Jetbrain. Well worth it to be honest.
@eliesamyoun1006
@eliesamyoun1006 Жыл бұрын
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?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
No - these are just unit tests. They don't touch the DB.
@ZeBobo5
@ZeBobo5 Жыл бұрын
You can use this csproj itemgroup item :
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Pretty cool, I wasn't aware of that
@Cornet435
@Cornet435 Жыл бұрын
Very nice video ☺️ Will you ever make a video about integration tests?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
At some point, definitely
@dxs1971
@dxs1971 Жыл бұрын
also you could fill repository with predefined email and than the test will have purpose
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Perhaps, but not what I tried to do in this video
@Senboni
@Senboni Жыл бұрын
I love me some xunit + moq combination 👌
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Awesome 🔥
@godwindiaba9122
@godwindiaba9122 4 ай бұрын
Thank you very much sir
@MilanJovanovicTech
@MilanJovanovicTech 4 ай бұрын
You are welcome
@jorgegarcia8843
@jorgegarcia8843 Жыл бұрын
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.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
No, but check out my Testcontainers video which runs the entire MediatR pipeline. Or you can unit test the command validator on its own.
@ifstatementifstatement2704
@ifstatementifstatement2704 Жыл бұрын
Client: “why did the project take twice as long?” Dev: “unit testing”
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
They'll thank you later when you don't need to do bug fixing
@ifstatementifstatement2704
@ifstatementifstatement2704 Жыл бұрын
@@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.
@AboutCleanCode
@AboutCleanCode Жыл бұрын
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?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
100% coverage should never be the goal by itself. The goal should be to write meaningful tests. And coverage will come on its own.
@amirpeeri
@amirpeeri Жыл бұрын
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!
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
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.
@bojanpavlovic5038
@bojanpavlovic5038 Жыл бұрын
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?
@PelFox
@PelFox Жыл бұрын
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.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
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.
@bojanpavlovic5038
@bojanpavlovic5038 Жыл бұрын
Yeah. In memory done the job well actually. But was curious to hear your opinion! Thanks!
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
@@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.
@bojanpavlovic5038
@bojanpavlovic5038 Жыл бұрын
I have made seed classes and a provider put all together and just load all in constructor. End up being very simple and easy
@jonaslewin
@jonaslewin Жыл бұрын
Please create more videos in your awesome Clean Architecture & DDD Series.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
They're on the way!
@PaulSebastianM
@PaulSebastianM Жыл бұрын
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
@MilanJovanovicTech Жыл бұрын
I don't practice TDD 🤷‍♂️ So it didn't make sense for me to start now. But I may try it for some video.
@tarekhaydar9795
@tarekhaydar9795 Жыл бұрын
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?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
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.
@PelFox
@PelFox Жыл бұрын
You should have one unit test project per library you create. Integration tests can go through everything from the api endpoints.
@100kshooter5
@100kshooter5 Жыл бұрын
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
@MilanJovanovicTech Жыл бұрын
Interesting idea. So basically two web apps, using the same projects underneath?
@100kshooter5
@100kshooter5 Жыл бұрын
@@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.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
@@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
@100kshooter5
@100kshooter5 Жыл бұрын
@@MilanJovanovicTech Amazing thank you. . .
@shuvbhowmickbestin
@shuvbhowmickbestin Ай бұрын
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.
@MilanJovanovicTech
@MilanJovanovicTech Ай бұрын
I wrote it myself, as it's not a lot of code. But there are a bunch of NuGet packages you can use: kzbin.info/www/bejne/eWLSeKF6etOGZ5Y
@Zainjerr
@Zainjerr Жыл бұрын
This is awesome!
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Thank you!
@erald_doka
@erald_doka Жыл бұрын
Hi Milan, What theme/colours are you using for the visual studio?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Hey! This is ReSharper dark theme
@joasengelberts594
@joasengelberts594 Жыл бұрын
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?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
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.
@murat.yuceer
@murat.yuceer Жыл бұрын
Hello Milan, Is there a repository where all the lessons you have done are collected?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
At the moment, I only share the code with my Patreon supporters. On occasion, I will post something on my GitHub also.
@murat.yuceer
@murat.yuceer Жыл бұрын
@@MilanJovanovicTech you can post all things
@shatvani
@shatvani Жыл бұрын
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.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
With Moq, you can configure the Get method to return a list of your choosing
@jarnohonkanen4321
@jarnohonkanen4321 Жыл бұрын
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?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Unit of Work video is coming out on Friday! 😁 And I'll tackle Entity Id generation in a separate video
@RavinderSingh-jx5sl
@RavinderSingh-jx5sl Жыл бұрын
Good videos, but how can we test FluentValidation?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
You can create a command and pass it to a validator instance for testing
@JulianoLambda
@JulianoLambda Жыл бұрын
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?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Domain Entities are DB Entities also, that's why. I don't create separate models.
@arpanmukherjee4625
@arpanmukherjee4625 9 ай бұрын
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)?
@MilanJovanovicTech
@MilanJovanovicTech 9 ай бұрын
Testing the entire flow = write an integration test Otherwise, you can mock the response and run with it
@shuvbhowmickbestin
@shuvbhowmickbestin Ай бұрын
And obviously VS2022 sets the project up with 99+ changes!
@MilanJovanovicTech
@MilanJovanovicTech Ай бұрын
Hmm?
@TrOgaN_
@TrOgaN_ 5 ай бұрын
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!
@MilanJovanovicTech
@MilanJovanovicTech 5 ай бұрын
We can always clear the DB before running the test
@TrOgaN_
@TrOgaN_ 5 ай бұрын
@@MilanJovanovicTech We can but we didn't, we didn't even mention the database.
@MilanJovanovicTech
@MilanJovanovicTech 5 ай бұрын
@@TrOgaN_ Check out a few videos I've done on integration testing
@TrOgaN_
@TrOgaN_ 5 ай бұрын
@@MilanJovanovicTech This isn't integration testing, it's unit testing jtbc. i'm reluctant to look at any more videos sorry!
@SabbirHossain-el2rv
@SabbirHossain-el2rv 5 ай бұрын
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.
@MilanJovanovicTech
@MilanJovanovicTech 5 ай бұрын
Use a proper DbContext
@y.5107
@y.5107 7 ай бұрын
How to test actions which simply execute dapper (CQRS) queries?
@MilanJovanovicTech
@MilanJovanovicTech 7 ай бұрын
Integration tests with Testcontainers
@y.5107
@y.5107 7 ай бұрын
@@MilanJovanovicTechso actually testing against the database? Seed the database and assert against the expected results?
@onedev7316
@onedev7316 Жыл бұрын
excellent. Have you got github link for above example?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Yes, but only for me Patreon supporters
@onedev7316
@onedev7316 Жыл бұрын
@@MilanJovanovicTech Patreon link please.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
@@onedev7316 www.patreon.com/milanjovanovic
@paulbarton2280
@paulbarton2280 Жыл бұрын
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.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
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.
@stefanbogdanovic590
@stefanbogdanovic590 Жыл бұрын
NSubstitute + Fluent Assertions + xUnit
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
How is NSubstitute compared to Moq?
@stefanbogdanovic590
@stefanbogdanovic590 Жыл бұрын
@@MilanJovanovicTech For me personally better and easier API to work with.
@CSharp_Dev2022
@CSharp_Dev2022 Жыл бұрын
Can you talk about docker
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Yes!
@CSharp_Dev2022
@CSharp_Dev2022 Жыл бұрын
@@MilanJovanovicTech It will be great if you talk about docker and how can we implemented in c#. Thank you
@CodeBallast
@CodeBallast Жыл бұрын
Why not just put the Arrange lines in the constructor. In that way you want have all your duplicate code.
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Good suggestion
@Eriksonlove69
@Eriksonlove69 Жыл бұрын
how can I get this repo?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Were you able to get access on Patreon?
@skarabei2303
@skarabei2303 8 ай бұрын
What if handler is void
@MilanJovanovicTech
@MilanJovanovicTech 8 ай бұрын
Test if the mocks were called with correct values
@dxs1971
@dxs1971 Жыл бұрын
Email should be ValueObject
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Isn't it?
@dxs1971
@dxs1971 Жыл бұрын
@@MilanJovanovicTech no it is just a string
@fernandocalmet
@fernandocalmet Жыл бұрын
Great video! Thank you Milan
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Thanks, Fernando! How do you write unit tests?
@fernandocalmet
@fernandocalmet Жыл бұрын
@@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😃
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
@@fernandocalmet Integration testing is definitely coming!
@richardaubin1951
@richardaubin1951 Жыл бұрын
Have you had a chance to use/review FakeItEasy?
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Only heard of it, never used it
@RichardONeil
@RichardONeil Жыл бұрын
This was great! Thanks!
@MilanJovanovicTech
@MilanJovanovicTech Жыл бұрын
Awesome. What's your approach?
Why I Use The Unit of Work Pattern With EF Core | Clean Architecture
11:34
Seja Gentil com os Pequenos Animais 😿
00:20
Los Wagners
Рет қаралды 16 МЛН
Сюрприз для Златы на день рождения
00:10
Victoria Portfolio
Рет қаралды 1,4 МЛН
She's very CREATIVE💡💦 #camping #survival #bushcraft #outdoors #lifehack
00:26
Kluster Duo #настольныеигры #boardgames #игры #games #настолки #настольные_игры
00:47
5x Your Cursor AI Coding Quality With These Pro Tips
16:34
YifanZ - Beyond the Hype
Рет қаралды 3,3 М.
Learn Unit Test with .Net 6 with xUnit and MOQ
1:29:24
Mohamad Lawand
Рет қаралды 32 М.
Coding Short: Is This Thing On? Testing APIs in .NET Core
19:33
Shawn Wildermuth
Рет қаралды 4,1 М.
The AI-Powered VS Code Killer? Checking Out Cursor and AI Coding
26:33
Milan Jovanović
Рет қаралды 19 М.
Don't Use Polly in .NET Directly. Use this instead!
14:58
Nick Chapsas
Рет қаралды 65 М.
Writing tests in .NET using xUnit -  xUnit Tutorial
25:50
Nick Chapsas
Рет қаралды 129 М.
Dependency Injection, The Best Pattern
13:16
CodeAesthetic
Рет қаралды 847 М.
Seja Gentil com os Pequenos Animais 😿
00:20
Los Wagners
Рет қаралды 16 МЛН