.NET MAUI – Forget Me Not – 7 – Unit Testing

Picking up where we left off, I want to add unit tests to my program. Now, I know, I should have been using unit tests all along. I have no excuse and hang my head in shame.

To get started, I’ve decided to add xUnit through NuGet. Easy peasy. But it won’t work. The full explanation is here. Great article. Here, in a nutshell are the steps you need to perform:

  1. Create an xUnit test project in the same solution as ForgetMeNot
  2. Make sure it runs
  3. Add a reference to the ForgetMeNot project
  4. This wil not run yet. Here is where the fun begins
  5. First, open up the ForgetMeNot project and change the TargetFrameworks to
<TargetFrameworks>net6.0;net6.0-android;net6.0-ios;net6.0-maccatalyst</TargetFrameworks>

6. Replace the output statement with

<OutputType Condition="'$(TargetFramework)' != 'net6.0'">Exe</OutputType>

7. Unload ForgetMeNot, reload it, close Visual Studio, open Visual Studio and voila! it will work

(The whys and wherefores are explained very well in the article referenced above)

NSubstitute for mocking

We are now almost ready to begin. I want to use mocking from the very beginning. Until about a weak ago, I’d have installed Moq, but I’m intrigued by NSubstitute, so I’m going to use that.

After assuring myself that the default xUnit test works, I’ll add a file called BuddyTests. In there I will add my first test: ShouldPopulateBuddies. I want to make sure that calling Init() will populate the list of buddies (actually, it could return no buddies, but right now I just want to get this test working).

 [Fact]
 public async Task ShouldPopulateBuddies()
 {
     var buddies = new List<Buddy>();
     var buddy = new Buddy();
     buddies.Add(buddy);
     var buddyService = Substitute.For<IBuddyService>();
     buddyService.GetBuddies().Returns(buddies);
     var buddyListVM = new BuddyListViewModel(buddyService);
     await buddyListVM.Init();
     Assert.True( buddyListVM.Buddies?.Count > 0);

 }

So what is going on here? First I create an empty list of Buddy objects and I create an instance of Buddy which I add to that list.

Next (and here is the cool part) I create a mock for my service with that one line

var buddyService = Substitute.For<IBuddyService>();

Remember that Substitute wants interfaces, so earlier I went to each class in my services, put the cursor on the class name and used Refactor->Extract->ExtractInterface which brought up this wonderful dialog box:

You are using Resharper, right??

I clicked on Select Public to get the public methods and Its own file to put the new interface in a file named IBuddyService.cs. R# is even nice enough to tack the interface name onto the class declaration.

OK, enough digression. My next step is to tell the mock that when the BuddyService’s GetBuddies method is returned, it should return the list of Buddies we just created.

We are now ready to create an instance of the ViewModel and call init() on it. It will use the service we passed in (the mock) and will thus populate its list of buddies with our dummy list and the Assert will pass.

Cool, eh?

This also tells me that I need to handle the case when the list is empty. That means I need to look long and hard at Init() and possibly add another test to prove that the corner case does not cause a problem.

Wrapping Up

It turns out that simple unit tests with mocking is not all that hard to do; and nSubstitute has a lot less ceremony than Moq. I’m going to stay with it for a while and see if I run off a cliff.

Since all the source code changes are already in this blog post, I won’t update the online source until I’ve written some more tests.

Shout-out to Daniel Hindrikes for helping me get started on unit testing for MAUI

See next posting for more unit testing using Fluent asserts.

Unknown's avatar

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. Liberty is a Senior AI Engineer at the University of Pittsburgh Medical Center, and was a Team Lead and Senior Software Engineer for various corporations, a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a 21 year Microsoft MVP.
This entry was posted in .NET MAUI, Essentials, Testing and tagged . Bookmark the permalink.

779 Responses to .NET MAUI – Forget Me Not – 7 – Unit Testing

  1. Henrytag's avatar Henrytag says:

    Следующая страница https://vodkabet-vbt.com

  2. Kevinvinge's avatar Kevinvinge says:

    amoxicillin buy no prescription: bacterial infection medication – amoxicillin 500

  3. Kevinvinge's avatar Kevinvinge says:

    stromectol delivery united states: buy stromectol online usa – parasite infection medication

  4. Keithdraiz's avatar Keithdraiz says:

    http://stericarepharmacy.com/# prednisone capsules

  5. Kevinvinge's avatar Kevinvinge says:

    brand prednisone: SteriCare Pharmacy – prednisone 20mg price

  6. AllenLew's avatar AllenLew says:

    https://ivermectinfast.shop/# ivermectin oral tablets usa

  7. Kevinvinge's avatar Kevinvinge says:

    where to buy prednisone 20mg no prescription: prednisone tablets 10mg 20mg – prednisone price australia

  8. AllenLew's avatar AllenLew says:

    https://stericarepharmacy.com/# prednisone 20mg tablets where to buy

  9. Kevinvinge's avatar Kevinvinge says:

    ivermectin treatment tablets: trusted ivermectin pharmacy – stromectol cost

  10. Jameslen's avatar Jameslen says:

    http://certifiedmaplerx.com/# certified canadian pharmacy usa

  11. DanielCeree's avatar DanielCeree says:

    canadian medication delivery to usa: canadian medication delivery to usa – certified canadian pharmacy usa

  12. JamesHEPLY's avatar JamesHEPLY says:

    http://bordervaluerx.com/# mexico border medications usa access

  13. JeffreyRuize's avatar JeffreyRuize says:

    mexico border medications usa access: mexican drugstore shipping to usa – the purple pharmacy mexico

  14. DanielCeree's avatar DanielCeree says:

    licensed canadian drug suppliers: vipps canadian pharmacy – canadian medication delivery to usa

  15. PhillipSem's avatar PhillipSem says:

    https://northcarerx.com/# canadapharmacyonline com

  16. PhillipSem's avatar PhillipSem says:

    https://primeindiameds.shop/# canada online pharmacy no prescription

  17. Edwardcom's avatar Edwardcom says:

    https://primeindiameds.shop/# prescription free canadian pharmacy

  18. Edwardcom's avatar Edwardcom says:

    https://primeindiameds.com/# mail order pharmacy india

  19. Richardroony's avatar Richardroony says:

    otc antibiotics Azithromycin Dihydrate get antibiotics without seeing a doctor

  20. RalphWok's avatar RalphWok says:

    uti antibiotics online Azithromycin Dihydrate buy antibiotics for sinus

  21. WilliamTAT's avatar WilliamTAT says:

    OTC antibiotics prescribed antibiotics online

  22. 爱一帆's avatar 爱一帆 says:

    Long range goals, strikes from outside the box documented

  23. RalphWok's avatar RalphWok says:

    buy antibiotics from india OTC antibiotics buy antibiotics online for tooth infection

  24. WilliamTAT's avatar WilliamTAT says:

    OTC antibiotics antibiotics

  25. EdwardPrany's avatar EdwardPrany says:

    pin up casino pin up

  26. Andreimiva's avatar Andreimiva says:

    cialis Pharmacological Sciences Research Institute Pharmacological Sciences

  27. Whitneysnolf's avatar Whitneysnolf says:

    where can i buy erectile dysfunction pills Pharmacological Institute buying erectile dysfunction pills online

  28. Williamnourl's avatar Williamnourl says:

    http://corevitalpharmacy.com/# CoreVital Pharmacy

  29. Whitneysnolf's avatar Whitneysnolf says:

    cheapest online ed treatment Pharmacological Institute ed medications online

  30. Arthurnor's avatar Arthurnor says:

    Buy generic 100mg Viagra online: NovaMen Pharmacy – Cheap Viagra 100mg

  31. Malcolmmomma's avatar Malcolmmomma says:

    Real-money games have become incredibly popular due to their sheer accessibility.
    Users can access their preferred games anytime and anywhere with an internet connection.
    The excitement of competing for real money introduces an additional layer of adrenaline.
    A massive array of options caters to every preference and skill level.
    Promotions and rewards schemes offer added incentives to keep players engaged.
    Today’s sites ensure secure transactions and regulated gaming experiences.
    https://www.hrdp-idrm.in/

  32. Arthurnor's avatar Arthurnor says:

    pills for ed online: ed pills pharmacy – buy ed meds online

  33. Hectorzenna's avatar Hectorzenna says:

    affordable ed medication: ed pills pharmacy – where can i get ed pills

  34. EdwardWaymn's avatar EdwardWaymn says:

    https://primelinepharmacy.shop/# get ed prescription online

  35. Patrickfuh's avatar Patrickfuh says:

    india online pharmacy: buy medicines online in india – india online pharmacy

  36. Patrickfuh's avatar Patrickfuh says:

    MedBridge Pharmacy: pharmaceutical online – MedBridge Pharmacy

  37. Thomassnice's avatar Thomassnice says:

    top 10 pharmacies in india: india pharmacy mail order – top online pharmacy india

  38. AnthonyJonry's avatar AnthonyJonry says:

    reputable online pharmacy buy Viagra online legitimate canadian pharmacies

  39. Elmerrit's avatar Elmerrit says:

    http://happypawspharmacy.com/# pet antibiotics and care

  40. RichardGit's avatar RichardGit says:

    canada drugs online: over the counter sildenafil – online pharmacy com

Comments are closed.