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

Поділитися
Вставка
  • Опубліковано 28 січ 2025

КОМЕНТАРІ • 141

  • @MilanJovanovicTech
    @MilanJovanovicTech  2 роки тому +6

    Want to master Clean Architecture? Go here: bit.ly/3PupkOJ
    Want to unlock Modular Monoliths? Go here: bit.ly/3SXlzSt

  • @kinggrizzly13
    @kinggrizzly13 2 роки тому +9

    XUnit tests - check
    Testing internal classes - check
    Exactly what I was looking for. Thank you!!!

  • @MarcusKaseder
    @MarcusKaseder 2 роки тому +18

    You can also write internals visible to with this shorthand:

  • @sergiom.954
    @sergiom.954 2 роки тому +11

    I didn't know about the internal visibility feature for test projects. Thanks Milan for your job.

  • @SajidAliSoftwareEngineer
    @SajidAliSoftwareEngineer 2 роки тому +6

    yes Millan we need more unit testing videos. Thank you so much for such nice video.

  • @martinbryant3515
    @martinbryant3515 2 роки тому +3

    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  2 роки тому +2

      This is pretty cool! Growing list of dependencies is indeed a big pain. I have to explore Automock more now 😁

  • @BEARMC27
    @BEARMC27 2 роки тому +1

    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  2 роки тому

      Awesome, glad you liked it. I took a look at Kotlin once, and it seemed very similar to ASP .NET

  • @milicabozic9897
    @milicabozic9897 2 роки тому +4

    Thank you, this will be very useful for my unit tests.

  • @calblui
    @calblui 2 роки тому +2

    Great job man! I'm learning a lot from your classes

  • @dotnetMasterCSharp
    @dotnetMasterCSharp Місяць тому

    this is useful for my clean architecture projects, thanks

  • @hamitkarahan2973
    @hamitkarahan2973 2 роки тому +1

    Nice video Milan, thanks for good contents!

  • @ibrahimhebish1404
    @ibrahimhebish1404 2 роки тому +6

    You did a great job Milan , it would be nice if we have a full series on testing

  • @woquendoG
    @woquendoG Рік тому +2

    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?

  • @ZeBobo5
    @ZeBobo5 2 роки тому +7

    You can use this csproj itemgroup item :

  • @y.5107
    @y.5107 11 місяців тому +2

    How to test actions which simply execute dapper (CQRS) queries?

    • @MilanJovanovicTech
      @MilanJovanovicTech  11 місяців тому

      Integration tests with Testcontainers

    • @y.5107
      @y.5107 11 місяців тому

      @@MilanJovanovicTechso actually testing against the database? Seed the database and assert against the expected results?

  • @Senboni
    @Senboni 2 роки тому +2

    I love me some xunit + moq combination 👌

  • @alexalexander3252
    @alexalexander3252 Рік тому +1

    Dam maaaaan, your left eyebrow move made me like your video, and right eyebrow move made me subscribe. Your are hypnotizer ot what?

  • @AboutCleanCode
    @AboutCleanCode 2 роки тому +2

    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  2 роки тому +1

      100% coverage should never be the goal by itself. The goal should be to write meaningful tests. And coverage will come on its own.

  • @jogadordejogos4041
    @jogadordejogos4041 2 роки тому +3

    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  2 роки тому +3

      Yes, I'm planning to release a course early next year :)

  • @RichardONeil
    @RichardONeil 2 роки тому +1

    This was great! Thanks!

  • @dxs1971
    @dxs1971 2 роки тому +1

    also you could fill repository with predefined email and than the test will have purpose

  • @ajaypanse4489
    @ajaypanse4489 11 місяців тому +2

    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  11 місяців тому

      This could be helpful: ua-cam.com/video/ikRPfoKl1SE/v-deo.html

  • @PaulSebastianM
    @PaulSebastianM 2 роки тому +3

    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  2 роки тому +1

      I don't practice TDD 🤷‍♂️ So it didn't make sense for me to start now. But I may try it for some video.

  • @ifstatementifstatement2704
    @ifstatementifstatement2704 2 роки тому +1

    Client: “why did the project take twice as long?”
    Dev: “unit testing”

    • @MilanJovanovicTech
      @MilanJovanovicTech  2 роки тому +1

      They'll thank you later when you don't need to do bug fixing

    • @ifstatementifstatement2704
      @ifstatementifstatement2704 2 роки тому

      @@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.

  • @jorgegarcia8843
    @jorgegarcia8843 Рік тому +1

    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  Рік тому +1

      No, but check out my Testcontainers video which runs the entire MediatR pipeline.
      Or you can unit test the command validator on its own.

  • @tarekhaydar9795
    @tarekhaydar9795 2 роки тому +1

    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  2 роки тому +1

      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 2 роки тому +1

      You should have one unit test project per library you create. Integration tests can go through everything from the api endpoints.

  • @shatvani
    @shatvani Рік тому +1

    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

  • @Yash42189
    @Yash42189 2 роки тому +2

    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  2 роки тому

      If you go back to the earliest videos, I start more or less from scratch

  • @shuvbhowmickbestin
    @shuvbhowmickbestin 4 місяці тому

    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  4 місяці тому +1

      I wrote it myself, as it's not a lot of code. But there are a bunch of NuGet packages you can use: ua-cam.com/video/C1oGnDEnS14/v-deo.html

  • @jarnohonkanen4321
    @jarnohonkanen4321 2 роки тому +1

    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  2 роки тому +4

      Unit of Work video is coming out on Friday! 😁
      And I'll tackle Entity Id generation in a separate video

  • @eliesamyoun1006
    @eliesamyoun1006 Рік тому +1

    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?

  • @murat.yuceer
    @murat.yuceer 2 роки тому +1

    Hello Milan, Is there a repository where all the lessons you have done are collected?

    • @MilanJovanovicTech
      @MilanJovanovicTech  2 роки тому

      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 2 роки тому

      @@MilanJovanovicTech you can post all things

  • @jonaslewin
    @jonaslewin 2 роки тому +1

    Please create more videos in your awesome Clean Architecture & DDD Series.

  • @godwindiaba9122
    @godwindiaba9122 8 місяців тому

    Thank you very much sir

  • @Zainjerr
    @Zainjerr 2 роки тому

    This is awesome!

  • @joasengelberts594
    @joasengelberts594 2 роки тому +1

    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  2 роки тому

      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.

  • @SabbirHossain-el2rv
    @SabbirHossain-el2rv 9 місяців тому

    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.

  • @erald_doka
    @erald_doka 2 роки тому +1

    Hi Milan, What theme/colours are you using for the visual studio?

  • @benjaminvenezia1944
    @benjaminvenezia1944 2 місяці тому

    Hi! Thank's for the great content! What is Result class you use to wrap Guid? Ty

    • @MilanJovanovicTech
      @MilanJovanovicTech  2 місяці тому

      Something like this: gist.github.com/m-jovanovic/aa25b1ae424c985ff8ae696a79b6fe6e

  • @arpanmukherjee4625
    @arpanmukherjee4625 Рік тому

    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  Рік тому

      Testing the entire flow = write an integration test
      Otherwise, you can mock the response and run with it

  • @bojanpavlovic5038
    @bojanpavlovic5038 2 роки тому +2

    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 2 роки тому

      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  2 роки тому +3

      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 2 роки тому +1

      Yeah. In memory done the job well actually. But was curious to hear your opinion! Thanks!

    • @MilanJovanovicTech
      @MilanJovanovicTech  2 роки тому +1

      @@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 2 роки тому

      I have made seed classes and a provider put all together and just load all in constructor. End up being very simple and easy

  • @100kshooter5
    @100kshooter5 2 роки тому +1

    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  2 роки тому

      Interesting idea. So basically two web apps, using the same projects underneath?

    • @100kshooter5
      @100kshooter5 2 роки тому +1

      @@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  2 роки тому +1

      @@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 2 роки тому +1

      @@MilanJovanovicTech Amazing thank you. . .

  • @TrOgaN_
    @TrOgaN_ 9 місяців тому

    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  9 місяців тому

      We can always clear the DB before running the test

    • @TrOgaN_
      @TrOgaN_ 9 місяців тому

      @@MilanJovanovicTech We can but we didn't, we didn't even mention the database.

    • @MilanJovanovicTech
      @MilanJovanovicTech  9 місяців тому

      @@TrOgaN_ Check out a few videos I've done on integration testing

    • @TrOgaN_
      @TrOgaN_ 9 місяців тому

      @@MilanJovanovicTech This isn't integration testing, it's unit testing jtbc. i'm reluctant to look at any more videos sorry!

  • @Cornet435
    @Cornet435 Рік тому +1

    Very nice video ☺️
    Will you ever make a video about integration tests?

  • @JulianoLambda
    @JulianoLambda 2 роки тому +1

    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  2 роки тому

      Domain Entities are DB Entities also, that's why. I don't create separate models.

  • @onedev7316
    @onedev7316 2 роки тому +1

    excellent. Have you got github link for above example?

  • @Eriksonlove69
    @Eriksonlove69 Рік тому +1

    how can I get this repo?

  • @vekzdran
    @vekzdran 2 роки тому +1

    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  2 роки тому

      I used dotCover for this, but it's a paid tool from Jetbrain. Well worth it to be honest.

  • @amirpeeri
    @amirpeeri 2 роки тому +1

    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  2 роки тому +2

      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.

  • @RavinderSingh-jx5sl
    @RavinderSingh-jx5sl Рік тому +1

    Good videos, but how can we test FluentValidation?

    • @MilanJovanovicTech
      @MilanJovanovicTech  Рік тому

      You can create a command and pass it to a validator instance for testing

  • @CSharp_Dev2022
    @CSharp_Dev2022 2 роки тому +1

    Can you talk about docker

    • @MilanJovanovicTech
      @MilanJovanovicTech  2 роки тому +1

      Yes!

    • @CSharp_Dev2022
      @CSharp_Dev2022 2 роки тому

      @@MilanJovanovicTech It will be great if you talk about docker and how can we implemented in c#. Thank you

  • @skarabei2303
    @skarabei2303 Рік тому

    What if handler is void

  • @stefanbogdanovic590
    @stefanbogdanovic590 2 роки тому +1

    NSubstitute + Fluent Assertions + xUnit

  • @CodeBallast
    @CodeBallast 2 роки тому +1

    Why not just put the Arrange lines in the constructor. In that way you want have all your duplicate code.

  • @shuvbhowmickbestin
    @shuvbhowmickbestin 4 місяці тому

    And obviously VS2022 sets the project up with 99+ changes!

  • @paulbarton2280
    @paulbarton2280 2 роки тому +2

    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  2 роки тому

      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.

  • @fernandocalmet
    @fernandocalmet 2 роки тому

    Great video! Thank you Milan

    • @MilanJovanovicTech
      @MilanJovanovicTech  2 роки тому +1

      Thanks, Fernando! How do you write unit tests?

    • @fernandocalmet
      @fernandocalmet 2 роки тому +1

      @@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  2 роки тому

      @@fernandocalmet Integration testing is definitely coming!

  • @dxs1971
    @dxs1971 2 роки тому +1

    Email should be ValueObject

  • @richardaubin1951
    @richardaubin1951 2 роки тому +1

    Have you had a chance to use/review FakeItEasy?

  • @EHBRod13
    @EHBRod13 2 роки тому +1

    Thanks for the video! Super helpful!