.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. Currently it appears like Expression Engine is the preferred blogging platform available right now. (from what I’ve read) Is that what you’re using on your blog?

  2. Arnold Ellis's avatar Arnold Ellis says:

    Hi there, You have performed an excellent job. I will certainly digg it and in my view recommend to my friends. I am sure they will be benefited from this site.

  3. An outstanding share! I have just forwarded this onto a colleague who has been doing a little homework on this. And he in fact bought me breakfast because I discovered it for him… lol. So let me reword this…. Thank YOU for the meal!! But yeah, thanks for spending the time to discuss this matter here on your blog.

  4. Wow that was strange. I just wrote an extremely long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say great blog!

  5. Sue Klink's avatar Sue Klink says:

    Hmm it looks like your website ate my first comment (it was super long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I too am an aspiring blog blogger but I’m still new to everything. Do you have any points for beginner blog writers? I’d genuinely appreciate it.

  6. Freddy Cantv's avatar Freddy Cantv says:

    Aw, this was an extremely good post. Spending some time and actual effort to create a superb article… but what can I say… I procrastinate a lot and never seem to get anything done.

  7. At this time it seems like Drupal is the best blogging platform out there right now. (from what I’ve read) Is that what you’re using on your blog?

  8. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  9. Bruna Lerew's avatar Bruna Lerew says:

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  10. I’m impressed, I must say. Seldom do I encounter a blog that’s equally educative and engaging, and let me tell you, you’ve hit the nail on the head. The issue is an issue that not enough folks are speaking intelligently about. I’m very happy I found this in my search for something regarding this.

  11. Сюрвей осадки — это способ измерения осадки судна для установления массы перевозимого товара.
    Данный подход базируется на физический закон вытеснения и даёт возможность расчёта объёма продукции по изменению водоизмещения.
    Измерение осуществляется до и после загрузки или выгрузки, чтобы зафиксировать реальное вес перемещённого товара.
    https://eurogal-surveys.ru/
    Действие подразумевает записи значений углубления в нескольких местах и внесения корректировок на плотность воды.
    Такой контроль широко применяется в экспортно-импортных операциях для коммерческих сверок и проверок.
    Это является надёжным инструментом проверки массы товаров, одобренным глобальными соглашениями.

  12. Nan Groening's avatar Nan Groening says:

    Right now it appears like BlogEngine is the preferred blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?

  13. Art Villela's avatar Art Villela says:

    Right now it seems like Expression Engine is the preferred blogging platform available right now. (from what I’ve read) Is that what you’re using on your blog?

  14. Maria Newson's avatar Maria Newson says:

    Wow that was odd. I just wrote an incredibly long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyhow, just wanted to say great blog!

  15. Hello! Someone in my Facebook group shared this website with us so I came to look it over. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Excellent blog and terrific design.

  16. Otto Mellon's avatar Otto Mellon says:

    Hello, I read your blog daily. Your humoristic style is awesome, keep doing what you’re doing!

  17. Tamra Mcguin's avatar Tamra Mcguin says:

    I think the admin of this web page is in fact working hard for his site, as here every stuff is quality based data.

  18. Hello there, I found your blog by way of Google at the same time as looking for a similar matter, your website got here up, it looks great. I’ve bookmarked it in my google bookmarks

  19. Wow that was strange. I just wrote an very long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say wonderful blog!

  20. Right here is the perfect website for anybody who wishes to understand this topic. You understand so much its almost tough to argue with you (not that I personally will need to…HaHa). You definitely put a new spin on a subject which has been discussed for decades. Wonderful stuff, just wonderful!

  21. May I just say what a comfort to find someone who truly knows what they’re talking about online. You definitely know how to bring a problem to light and make it important. More and more people must check this out and understand this side of your story. I was surprised that you aren’t more popular given that you most certainly have the gift.

  22. Sol Vidler's avatar Sol Vidler says:

    Currently it looks like Drupal is the best blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?

  23. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  24. Bruna Andert's avatar Bruna Andert says:

    Hello would you mind letting me know which webhost you’re utilizing? I’ve loaded your blog in 3 different browsers and I must say this blog loads a lot quicker then most. Can you suggest a good web hosting provider at a honest price? Cheers, I appreciate it!

  25. Tuan Went's avatar Tuan Went says:

    Thanks for your marvelous posting! I actually enjoyed reading it, you will be a great author.I will remember to bookmark your blog and definitely will come back sometime soon. I want to encourage one to continue your great work, have a nice holiday weekend!

  26. Shaunna's avatar Shaunna says:

    Right now it looks like Movable Type is the preferred blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?

  27. Mathilda's avatar Mathilda says:

    At this time it appears like Drupal is the preferred blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?

Comments are closed.