.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. Aw, this was a very good post. Finding the time and actual effort to produce a great article… but what can I say… I procrastinate a lot and don’t manage to get nearly anything done.

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

  3. Greate article. Keep writing such kind of information on your blog. Im really impressed by your site.

  4. Метод УВТ представляет собой современный метод воздействия, основанный на применении звуковых импульсов.
    Эта техника активизирует кровообращение и ускоряет механизмы восстановления клеток.
    УВТ широко используется для купирования патологий суставов и связок – в частности, при воспалении сухожилий и пяточной шпоре.
    https://novogireevo-klinika.ru/
    Главные преимущества метода – это отсутствие разрезов, относительная терпимость и хорошая эффективность уже после первых сеансов.
    Как правило сеанс занимает примерно 10–20 минут и проводится в поликлинике без необходимости стационара.
    По окончании курса больные отмечают значительное уменьшение болей и возвращение объёма подвижности в проблемной области.

  5. Larryher's avatar Larryher says:

    https://pharmmex.sbs/# progreso mexico pharmacy online

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

  7. 雷泽登录's avatar 雷泽登录 says:

    Hey there, You’ve done a great job. I’ll certainly digg it and in my view recommend to my friends. I am sure they will be benefited from this website.

  8. 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!

  9. Hi there, You’ve performed an incredible job. I will certainly digg it and in my opinion recommend to my friends. I’m confident they will be benefited from this website.

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

  11. Hi there, You have performed a great job. I’ll definitely digg it and individually suggest to my friends. I am confident they will be benefited from this web site.

  12. Aw, this was a really good post. Spending some time and actual effort to create a great article… but what can I say… I put things off a whole lot and don’t seem to get anything done.

  13. Проктологическая проблема нуждается в своевременного лечения, поскольку прогрессирующий процесс ведёт к последствиям.
    Без правильной терапии симптомы нарастают: боль, зуд и выделения становятся невыносимыми.
    Патология способна спровоцировать тромбоз вен, малокровие и даже воспаление близлежащих тканей.
    копчик болит при сидении у мужчин
    Терапия на начальных этапах позволяет применять малоинвазивные способы, избегая операционного вмешательства.
    Нынешние препараты и процедуры обеспечивают быстрый эффект и минимум болевых ощущений для пациента.
    Раннее посещение к проктологу помогает нормализовать качество повседневного существования и избежать тяжёлых осложнений.

  14. Hey there, You’ve done an incredible job. I’ll definitely digg it and in my opinion suggest to my friends. I’m sure they’ll be benefited from this web site.

  15. Геморрой требует незамедлительного терапии, так как запущенный стадия ведёт к последствиям.
    При отсутствии правильной помощи симптомы нарастают: боль, зуд и выделения оказываются постоянными.
    Заболевание может вызвать закупорку узлов, малокровие и даже воспаление окружающих зон.
    что означает слизь в кале
    Терапия на начальных ступенях позволяет применять консервативные способы, избегая операционного вмешательства.
    Современные средства и манипуляции обеспечивают скоростной результат и незначительный дискомфорт для пациента.
    Раннее посещение к врачу помогает нормализовать качество жизни и избежать серьёзных последствий.

  16. The other day, while I was at work, my cousin stole my iphone and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is completely off topic but I had to share it with someone!

  17. The other day, while I was at work, my sister stole my apple ipad and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views. I know this is totally off topic but I had to share it with someone!

  18. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://www.binance.bh/register?ref=GGYHGRE

  19. Simply want to say your article is as amazing. The clarity in your post is simply cool and i could assume you are an expert on this subject. Well with your permission let me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please carry on the gratifying work.

  20. Just desire to say your article is as amazing. The clearness in your post is just nice and i can assume you’re an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please continue the gratifying work.

  21. Simply desire to say your article is as surprising. The clearness in your post is just great and i can assume you’re an expert on this subject. Well with your permission allow me to grab your feed to keep updated with forthcoming post. Thanks a million and please keep up the enjoyable work.

  22. Simply desire to say your article is as astonishing. The clarity in your post is simply great and i can assume you’re an expert on this subject. Well with your permission allow me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please carry on the gratifying work.

  23. Simply desire to say your article is as surprising. The clearness in your post is simply great and i can assume you’re an expert on this subject. Well with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please carry on the rewarding work.

  24. I like this website its a master peace ! .

  25. Excellent article. Keep posting such kind of info on your page. Im really impressed by your blog.

  26. Thanks for the marvelous posting! I seriously enjoyed reading it, you’re a great author.I will be sure to bookmark your blog and will often come back sometime soon. I want to encourage that you continue your great job, have a nice weekend!

  27. Greate article. Keep posting such kind of info on your blog. Im really impressed by it.

  28. At this time it appears like Expression Engine is the preferred blogging platform out there right now. (from what I’ve read) Is that what you’re using on your blog?

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

  30. Dennisves's avatar Dennisves says:

    подробнее здесь водкабет

  31. Dennisves's avatar Dennisves says:

    посетить сайт vodkabet

  32. Currently it looks 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?

  33. An outstanding share! I’ve just forwarded this onto a coworker who was doing a little research on this. And he actually ordered me lunch simply because I stumbled upon it for him… lol. So allow me to reword this…. Thanks for the meal!! But yeah, thanx for spending the time to discuss this subject here on your site.

  34. Right now it sounds like WordPress is the best blogging platform available right now. (from what I’ve read) Is that what you’re using on your blog?

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

  36. Hi there! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no data backup. Do you have any solutions to prevent hackers?

  37. Richardkig's avatar Richardkig says:

    Svenska Pharma: recept pГҐ nГ¤tet – sjukhus apotek

  38. MichaelSet's avatar MichaelSet says:

    hette ett apotek saltlГ¶sning piercing apotek Svenska Pharma

  39. At this time it sounds 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?

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

  41. Great blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple adjustements would really make my blog jump out. Please let me know where you got your design. Thank you

  42. Excellent goods from you, man. I’ve be aware your stuff prior to and you’re just too wonderful. I actually like what you’ve got here, certainly like what you’re stating and the best way by which you assert it. You’re making it entertaining and you continue to take care of to stay it sensible. I cant wait to read much more from you. This is actually a great website.

  43. What’s up, everything is going well here and ofcourse every one is sharing data, that’s actually excellent, keep up writing.

  44. This info is invaluable. How can I find out more?

  45. Robertscals's avatar Robertscals says:

    Viagra homme prix en pharmacie sans ordonnance: Viagra femme ou trouver – Viagra vente libre allemagne

  46. sericit_kzEr's avatar sericit_kzEr says:

    крошка змеевик зеленая 10-20 мм крошка змеевик зеленая 10-20 мм

  47. Hi there, You’ve performed a great job. I’ll definitely digg it and in my view suggest to my friends. I’m sure they’ll be benefited from this website.

  48. Stevennut's avatar Stevennut says:

    проверить сайт трип скан

Comments are closed.