.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. Josephned's avatar Josephned says:

    amoxicillin price canada Infectious Disease & Antimicrobial Research Institute where can you get amoxicillin

  2. Thumbs up! Interesting content. A few of my classmates have been telling me about this blog to me for a while now and I finally decided to give it a look. You’ve made my day! Thx again. I used Xanax Coupon You appear to know a lot about this. Hit me up! Oh my gosh! A excellent article. Interesting content. You’ve made my day! Thx again. Great post! A few of my classmates have been recommending your website to me for some time now so I finally decided to check it out. You are a very persuasive writer. I have been looking everywhere for this! It’s like you read my thoughts! A few of my coworkers have been recommending this blog to me for some time now so I finally decided to check it out. You’ve made my day! Thx again.

  3. spinbet's avatar spinbet says:

    Informative article, totally what I wanted to find.

  4. 1win's avatar 1win says:

    Hello, always i used to check weblog posts here in the early hours in the break of day, for the reason that i love to learn more and more.

  5. spank me's avatar spank me says:

    This is an excellent, an eye-opener for sure!

  6. phwin's avatar phwin says:

    I’m gone to tell my little brother, that he should also pay a visit this webpage on regular basis to take updated from latest gossip.

  7. 7cslot's avatar 7cslot says:

    Your style is unique in comparison to other folks I have read stuff from. Thanks for posting when you’ve got the opportunity, Guess I will just book mark this blog.

  8. black face's avatar black face says:

    I truly appreciate this post. Your name is always mentioned when I talk with people about this topic. I’ve never done this for myself but I’ve been told by friends that it can be really helpful. Great post! The people at best solution are a rip off Google professionals would like your blog. Hit me up! This is an excellent, an eye-opener for sure! Hit me up! I enjoyed reading what you had to say. Your blog is always mentioned when I talk with people about this topic. I truly appreciate this post. I enjoyed reading this. Google pros would love your article. You are a very persuasive writer. You are obviously very knowledgeable. I enjoyed reading this.

  9. TimothySet's avatar TimothySet says:

    п»їbuy liraglutide glp-1 agonists

  10. JohnnieMut's avatar JohnnieMut says:

    п»їbuy liraglutide orlistat

  11. BryceTew's avatar BryceTew says:

    can you cut rybelsus us obesity science

  12. JohnnieMut's avatar JohnnieMut says:

    semaglutide dosage schedule American Metabolic Research Institute

  13. Home based's avatar Home based says:

    It’s like you wrote the book on it or something.

  14. jili777's avatar jili777 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.

  15. betflik's avatar betflik says:

    Hey there just wanted to give you a quick heads up and let you know a few
    of the images aren’t loading correctly. I’m not sure why
    but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome.
    betflik

  16. hiteBize's avatar hiteBize says:

    На этом этом портале имеется актуальная материалы.
    На этом портале есть возможность почерпнуть много практичного для себя.
    Представленный веб-сайт способен помочь изучить в разных проблемах.
    Рекомендуем подробно посмотреть опубликованные на этом сайте публикации.
    https://graph.org/Bvlgari-Watches-01-12

  17. Andrewkes's avatar Andrewkes says:

    Getting drugs online is extremely easy.
    One can shop 24/7 without leaving home.
    Digital drugstores let you quickly check costs and locate the best price.
    Your meds are delivered directly to your door, cutting time and effort.
    sildenafil stroke risk
    There’s no need to wait in annoying queues at a brick-and-mortar store.
    For chronic conditions, automatic refills ensure therapy stress‑free.
    Overall, digital shopping for medicine preserves your hours and peace of mind.

  18. Andrewkes's avatar Andrewkes says:

    Buying drugs online is very easy.
    You can purchase around the clock with no leaving home.
    Internet drugstores allow you to easily compare costs and find the lowest price.
    Your order are shipped straight to your door, cutting a trip and hassle.
    kamagra polo dosing guide
    There is no need to wait in endless lines at a local store.
    When dealing with long-term illnesses, auto refills ensure treatment stress‑free.
    Overall, digital shopping for meds saves your hours and energy.

  19. bets 10's avatar bets 10 says:

    I savor, lead to I discovered just what I used to be having a look for. You’ve ended my 4 day lengthy hunt! God Bless you man. Have a great day. Bye

  20. A person essentially lend a hand to make critically articles I’d state. This is the very first time I frequented your website page and to this point? I surprised with the analysis you made to make this particular publish amazing. Excellent job!

  21. Your article helped me a lot, is there any more related content? Thanks!

  22. casino bonus's avatar casino bonus says:

    I have been looking everywhere for this! It’s like you wrote the book on it or something. I really like your article. You’ve made my day! Thx again. The people at best product are a bunch of scumbags. This is an excellent, an eye-opener for sure! I truly appreciate this post. This is an excellent, an eye-opener for sure! Fantastic blog! You’ve made my day! Thx again. You are a very persuasive writer. I really like your article. Your article has proven useful to me. You’re an awesome story teller. Interesting content. People often ask me, Would I go back to that if I could? No way, things are way better today. You’ve made my day! Thx again.

  23. AnthonyJoiff's avatar AnthonyJoiff says:

    buy Viagra online Buy Viagra online cheap – Cheapest Sildenafil online

  24. DavidFraSe's avatar DavidFraSe says:

    Sildenafil Citrate Tablets 100mg cheapest viagra – buy Viagra online

  25. Jessegaf's avatar Jessegaf says:

    http://liraglutideglp1.com/# generic liraglutide

  26. 1win's avatar 1win says:

    Parei em R$340. Boa noite.

  27. Rollover cleared. Cashout in.

  28. Jessegaf's avatar Jessegaf says:

    http://semaglutideglp1.com/# rybelsus vs trulicity

  29. GeorgeGog's avatar GeorgeGog says:

    when to take rybelsus glp-1 drugs injectable semaglutide

  30. Os clipes de max win do Dim Sum Prize enganam — sessão média é bem mais calma.

  31. Beneficiary's avatar Beneficiary says:

    Thanks for writing this.

  32. ChrisTok's avatar ChrisTok says:

    viagra canada generic sildenafil sildenafil over the counter

  33. BrandonHoomb's avatar BrandonHoomb says:

    Правильный выбор корпоративной обстановки напрямую сказывается на самочувствие и работоспособность персонала.
    Ключевой критерий — это эргономичность cтульев и столов.
    Добротная корпусная мебель способна уменьшать усталость и предотвращать заболевания позвоночника.
    Точно так же важен эстетический вид предметов, ведь он создаёт имидж компании для клиентов и посетителей.
    https://n4.vladtoday.ru/redirect.php?id=A9ObZo9ZgU
    Стоит обращать внимание на сырьё: натуральное дерево, прочный металл и экологичные пропитки.
    Практичность предметов мебели проявляется в организации ящиков и настроек под индивидуальные задачи.
    Бюджет также имеет роль, но скупость на этих изделиях может привести к скрытым издержкам на ремонт или больничные.
    Поэтому, предпочитайте надёжных вендоров с гарантией и документацией соответствия.

  34. Sessão rápida. Saída rápida. Melhor tipo.

  35. Please let me know if you’re looking for a article writer for your weblog.
    You have some really good articles and I feel
    I would be a good asset. If you ever want to take some of the
    load off, I’d really like to write some material for your blog in exchange for a link back to mine.
    Please send me an e-mail if interested. Kudos!

  36. Today saw a solid result print on Ganesha Gold with a small bankroll and clean execution.

  37. Wow, superb blog layout! How long have you been blogging for?
    you make blogging look easy. The overall look of your site is magnificent, as well as the content!

  38. Ответственная игра в онлайн-казино представляет собой управление над временем и деньгами.
    Такая политика позволяет пользователю оставаться в пределах собственного лимита.
    Основные правила содержат установку сумм, перерывы в сессии и самопроверку.
    Механизмы добросовестной игры дают установить ограничения на пополнения и проигрыши.
    Такой метод защищает от аддикции и необдуманных трат.
    Участнику важно относиться к игре как к развлечению, а не способу заработка.
    Таким образом, здоровая игра превращает i-gaming в безопасное развлечение.
    vovan casino онлайн

  39. KennethEmbef's avatar KennethEmbef says:

    https://cialis.sbs/# Cialis over the counter

  40. Jamesmot's avatar Jamesmot says:

    https://rybelsus.pro/# can you split rybelsus tablets

  41. hiteBize's avatar hiteBize says:

    На этом этом портале содержится нужная статьи.
    Тут можно найти немало ценного для себя.
    Данный веб-сайт дает возможность изучить в многих ситуациях.
    Советуем внимательно изучить опубликованные тут публикации.
    https://permgorod.ru/novosti/188-dizayn-i-arkhitektura-pochemu-royal-oak-stali-ikonoy/

  42. KevinFup's avatar KevinFup says:

    ivermectin tablets order: stromectol 3mg tablets – ivermectin eye drops

Comments are closed.