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

    low cost ed medication ed pills online online ed pills

  2. RichardGit's avatar RichardGit says:

    canadian pharmacy sarasota: Generic Viagra online – on line pharmacy

  3. MartinEngam's avatar MartinEngam says:

    https://mostbettr.blog/# mostbet resmi giriş

  4. MartinEngam's avatar MartinEngam says:

    mostbet resmi: mostbet

  5. CurtisInses's avatar CurtisInses says:

    https://cassiteleri.top/# deneme bonusu veren casino siteleri

  6. Arisha37sr's avatar Arisha37sr says:

    Hello colleagues
    Hello. A 37 great website 1 that I found on the Internet.
    Check out this website. There’s a great article there. https://www.eslife.es/deportes-y-tragaperras|

    There is sure to be a lot of useful and interesting information for you here.
    You’ll find everything you need and more. Feel free to follow the link below.

  7. Shawnswarp's avatar Shawnswarp says:

    Looking well projects a positive first impression.
    Your outfit speaks loudly before a person even say a word.
    It boosts your personal self-esteem and mood significantly.
    Your put-together appearance signals professionalism in the workplace.
    https://dave.qrmoda.ru/the-influence-of-piaget-on-modern-watch-design-6914084/
    Fashionable clothing allow you to express your individual personality.
    Others often perceive well-dressed individuals as more successful and trustworthy.
    Ultimately, investing in your style is an valuable step in your personal brand.

  8. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://www.binance.com/register?ref=IHJUI7TF

  9. Nadine's avatar Nadine says:

    ข้อมูลชุดนี้ อ่านแล้วได้ความรู้เพิ่ม ครับ
    ผม ได้อ่านบทความที่เกี่ยวข้องกับ หัวข้อที่คล้ายกัน
    ที่คุณสามารถดูได้ที่ Nadine
    สำหรับใครกำลังหาเนื้อหาแบบนี้
    มีตัวอย่างประกอบชัดเจน
    ขอบคุณที่แชร์ ข้อมูลที่มีประโยชน์ นี้
    และหวังว่าจะได้เห็นโพสต์แนวนี้อีก

  10. Hey there, You have performed an incredible job. I will certainly digg it and in my opinion recommend to my friends. I’m sure they’ll be benefited from this site.

  11. Danielhic's avatar Danielhic says:

    Подготовка домашнего задания помогает усвоить материал, пройденный в школе.
    Это развивает навыки самостоятельной работы и обработки информации.
    Регулярное выполнение домашних заданий воспитывает чувство ответственности и планирования.
    Домашние работа позволяет родителям понимать успехи и пробелы ученика в учёбе.
    Русский язык 10 класс Гусарова решебник

  12. Howdy would you mind sharing which blog platform you’re working with? I’m looking to start my own blog soon but I’m having a tough time making a decision between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something unique. P.S My apologies for getting off-topic but I had to ask!

  13. Richardquatt's avatar Richardquatt says:

    Looking well creates a positive first impression.
    A attire communicates loudly before a person actually speak a single word.
    It enhances your personal self-esteem and mindset noticeably.
    Your put-together appearance signals competence in the workplace.
    https://truemanstyle.blogspot.com/2026/02/dolce.html
    Fashionable choices allow you to express your individual personality.
    Others often perceive well-dressed people as more capable and trustworthy.
    Therefore, putting effort in your wardrobe is an valuable step in your personal brand.

  14. Richardquatt's avatar Richardquatt says:

    Dressing stylish projects a positive first impression.
    A outfit speaks volumes before a person actually say a word.
    This enhances your personal self-esteem and mindset noticeably.
    A polished appearance signals competence in the office.
    https://riminisalon.ru/stati/zhenskoe-plate-simvol-jelegantnosti-i-vyrazhenie-individualnosti/
    Fashionable choices let you to showcase your individual personality.
    Others often perceive well-dressed individuals as more capable and trustworthy.
    Ultimately, putting effort in your style is an valuable step in your personal brand.

  15. Richardquatt's avatar Richardquatt says:

    Dressing well projects a strong first impression.
    A attire communicates volumes before you even speak a single word.
    It boosts your personal self-esteem and mood significantly.
    Your polished appearance signals professionalism in the office.
    https://u4.superpodium.com/FJxZzoX4wj/
    Fashionable clothing allow you to express your individual identity.
    Others often perceive well-dressed people as more capable and trustworthy.
    Ultimately, investing in your wardrobe is an valuable step in your personal brand.

  16. Richardquatt's avatar Richardquatt says:

    Looking well creates a positive first impression.
    A outfit communicates loudly before a person actually say a single word.
    It boosts your personal confidence and mindset significantly.
    A put-together appearance signals competence in the office.
    https://style.balmain1.ru/bieniya-atoma-anatomiya-chasov-richard-mille/
    Stylish choices allow you to showcase your individual identity.
    Others often perceive well-dressed people as more successful and reliable.
    Therefore, putting effort in your wardrobe is an investment in your personal brand.

  17. Richardquatt's avatar Richardquatt says:

    Looking well projects a strong first impression.
    A attire speaks loudly before a person actually say a single word.
    This boosts your personal self-esteem and mindset significantly.
    A polished look conveys professionalism in the workplace.
    https://b1.chenews.ru/ykrZogNx5FGj/
    Fashionable clothing let you to showcase your individual personality.
    Others often judge stylish people as more successful and reliable.
    Ultimately, putting effort in your wardrobe is an valuable step in your personal brand.

  18. Richardquatt's avatar Richardquatt says:

    Looking well projects a positive first impression.
    A outfit communicates loudly before you even speak a single word.
    It enhances your own confidence and mood significantly.
    Your put-together look signals professionalism in the office.
    https://links.sneakero.ru/JEIOspvUgin5/
    Stylish clothing allow you to showcase your individual identity.
    People often perceive well-dressed people as more capable and trustworthy.
    Ultimately, investing in your wardrobe is an valuable step in your personal brand.

  19. Richardquatt's avatar Richardquatt says:

    Looking stylish projects a strong first impression.
    Your outfit communicates volumes before a person actually speak a single word.
    This boosts your personal self-esteem and mindset significantly.
    A polished look signals professionalism in the workplace.
    https://u3.superpodium.com/erXJNLK1/
    Stylish choices allow you to express your individual personality.
    People often judge well-dressed individuals as more capable and reliable.
    Ultimately, investing in your style is an investment in yourself.

  20. Richardquatt's avatar Richardquatt says:

    Dressing stylish creates a strong first impression.
    Your outfit communicates loudly before a person even speak a single word.
    This enhances your personal confidence and mindset noticeably.
    Your put-together look signals professionalism in the office.
    https://u3.superpodium.com/erXJNLK1/
    Fashionable choices allow you to express your unique personality.
    People often perceive well-dressed people as more successful and reliable.
    Therefore, putting effort in your style is an investment in yourself.

  21. WilliamCig's avatar WilliamCig says:

    Luxury watches continue to hold strong appeal despite the rise of digital devices.
    They are often seen as a sign of prestige and refined taste.
    Expert workmanship plays a major role in their lasting value.
    Many luxury watches are produced using premium components.
    https://app.readthedocs.org/profiles/AromaCodex/
    They also represent a deep history passed down through generations.
    For collectors, these watches can serve as both practical items and valuable assets.
    Classic aesthetics allows them to stay relevant across changing fashion trends.
    Ultimately, luxury watches continue to appeal to enthusiasts around the world.

  22. Richardquatt's avatar Richardquatt says:

    Dressing well creates a strong first impression.
    Your attire speaks volumes before you even say a single word.
    This boosts your own self-esteem and mood significantly.
    Your polished appearance signals competence in the office.
    https://n6.sneakero.ru/f3kfnCJIj/
    Fashionable choices allow you to express your unique personality.
    Others often perceive stylish individuals as more successful and trustworthy.
    Therefore, investing in your wardrobe is an investment in your personal brand.

  23. Richardquatt's avatar Richardquatt says:

    Dressing well projects a positive first impression.
    A attire speaks loudly before you actually speak a word.
    It boosts your own self-esteem and mindset noticeably.
    Your polished appearance signals competence in the workplace.
    https://b1.chenews.ru/2yKQo43/
    Stylish choices allow you to showcase your individual personality.
    People often judge well-dressed individuals as more capable and reliable.
    Ultimately, investing in your wardrobe is an valuable step in your personal brand.

  24. Richardquatt's avatar Richardquatt says:

    Dressing well creates a strong first impression.
    Your outfit communicates volumes before you even speak a word.
    This enhances your own confidence and mindset significantly.
    A put-together appearance signals competence in the workplace.
    https://a4.megakazan.ru/wkp3MMb0BBC/
    Fashionable clothing allow you to express your unique personality.
    People often judge well-dressed people as more capable and reliable.
    Therefore, investing in your style is an valuable step in your personal brand.

  25. Richardquatt's avatar Richardquatt says:

    Looking well projects a positive first impression.
    Your outfit communicates volumes before a person actually say a single word.
    It enhances your own self-esteem and mood significantly.
    Your polished appearance signals competence in the workplace.
    https://b3.hypebeasts.ru/TjZG8d5Jp/
    Stylish clothing let you to showcase your unique identity.
    People often judge well-dressed people as more capable and reliable.
    Ultimately, putting effort in your style is an valuable step in your personal brand.

  26. After looking into a number of the blog articles on your blog, I really appreciate
    your way of writing a blog. I saved it to my bookmark webpage list and will be checking back in the near future.

    Please check out my web site too and let me
    know how you feel.

  27. Greetings from California! I’m bored to death at work so I decided to
    browse your site on my iphone during lunch break.
    I enjoy the information you present here and can’t wait
    to take a look when I get home. I’m surprised at how fast your blog loaded on my
    cell phone .. I’m not even using WIFI, just 3G ..
    Anyways, great blog!

  28. Tv888's avatar Tv888 says:

    This piece of writing will assist the internet people for setting up new webpage or even a blog from start to end.

  29. 8S's avatar 8S says:

    Hi there! This is my first visit to your blog! We are a collection of volunteers and starting a
    new initiative in a community in the same niche. Your blog provided us beneficial information to
    work on. You have done a marvellous job!

  30. This site truly has all the information and facts I needed concerning
    this subject and didn’t know who to ask.

  31. Winstongog's avatar Winstongog says:

    It isn’t separate from life—it’s the current running through every hour.
    With so much information, the meaning often gets diluted.
    What should be individual is presented as “one-size-fits-all”.
    Understanding grows when we make room for awareness.
    Our systems adapt and recalibrate day by day.
    Attention reveals details we didn’t know were there.
    Simple acts—eating, walking, breathing—turn into points of connection.
    By watching patterns, we learn how health responds to stress, time, and emotion.
    If you want to trust your signals again.
    To recognize the quiet patterns shaping your well-being.
    It’s about understanding rather than urgency.
    When we reflect, we see that the smallest signals can hold the biggest lessons.
    And it becomes even clearer when we focus on one topic in particular.
    All of these reflections naturally bring us to sildenafil expiration.

  32. Stevenhifup's avatar Stevenhifup says:

    Online number rental is a convenient service for modern communication needs.
    It allows users to handle calls without using a physical SIM card.
    Such a service is often selected for online registrations.
    Choosing this service helps protect personal privacy.
    https://www.easyworknet.net/technology/mobile-apps/how-to-benefit-from-using-virtual-number-for-text-messaging/
    The process is easy to understand and usually requires minimal time.
    Virtual numbers are suitable across different platforms.
    This solution offers flexibility for both temporary and long-term tasks.
    In general, virtual number rental continues to gain popularity among users worldwide.

  33. wow388's avatar wow388 says:

    Fantastic goods from you, man. I’ve understand your stuff previous to and you are just extremely
    fantastic. I actually like what you’ve acquired here, certainly
    like what you’re saying and the way in which you say it.
    You make it entertaining and you still take care of to keep it
    smart. I can’t wait to read far more from you. This
    is actually a tremendous web site.

  34. Howdy, i read your blog from time to time and i own a similar one and i was just wondering if you get a lot of spam feedback? If so how do you reduce it, any plugin or anything you can advise? I get so much lately it’s driving me crazy so any support is very much appreciated.

  35. buy traffic's avatar buy traffic says:

    Someone essentially help to make significantly articles I’d state. This is the very first time I frequented your website page and thus far? I amazed with the research you made to make this particular put up amazing. Wonderful task!

  36. Jamestrorb's avatar Jamestrorb says:

    Знакомство с новостными источниками играет важную роль в современном обществе.
    Оно помогает следить за актуальными новостями и ориентироваться в ситуации.
    Свежие материалы позволяют оценивать события.
    Чтение СМИ способствует расширению кругозора.
    https://telegra.ph/Novosibirsk-12-25-8
    Разнообразные медиа помогают видеть картину шире.
    В профессиональной сфере СМИ дают возможность оставаться конкурентоспособным.
    Осознанное потребление информации формирует умение работать с данными.
    В итоге, чтение СМИ помогает лучше понимать мир.

  37. Williamkak's avatar Williamkak says:

    Having a sense of style is important for creating a positive impression.
    A thoughtful appearance helps show personal taste.
    Stylish clothing can increase self-assurance.
    In everyday life, appearance often shapes first impressions.
    https://graph.org/Zara-01-12-2
    Carefully selected clothing make social situations more comfortable.
    It is important to consider personal preferences as well as the occasion.
    Fashion trends give people the chance to discover new ideas.
    In conclusion, dressing stylishly supports a complete personal image.

  38. livescore's avatar livescore says:

    統一獅賽程、戰績、球員數據,運用先進AI預測演算法一應俱全,讓您隨時掌握最愛球隊的最新動態。

  39. DavidFrase's avatar DavidFrase says:

    Петербург является значимым мегаполисом России.
    Город расположен на берегах Невы и известен своей историей.
    Городской облик сочетает классические постройки и современные кварталы.
    Санкт-Петербург славится музеями и насыщенной программой.
    Петербургские улицы создают особую атмосферу.
    Гости города приезжают сюда круглый год, чтобы насладиться красотой.
    Город является крупным транспортным узлом.
    В итоге, Санкт-Петербург считается особенным местом.
    https://www.trustami.com/review/69538625cc96c5ce448b457a-rating

  40. Really fantastic visual appeal on this internet site, I’d value it 10 10.

  41. WEB TRAFFIC's avatar WEB TRAFFIC says:

    I real pleased to find this web site on bing, just what I was looking for : D besides saved to my bookmarks.

  42. Davidpoeds's avatar Davidpoeds says:

    Having a sense of style is essential for building a personal image.
    A thoughtful appearance helps highlight individuality.
    Stylish clothing can boost confidence.
    In everyday life, appearance often shapes first impressions.
    https://telegra.ph/Bottega-Veneta-12-25-14
    Balanced style choices make professional interactions smoother.
    It is important to consider one’s own comfort as well as the occasion.
    Modern styles give people the chance to experiment with looks.
    Overall, dressing stylishly helps people feel confident.

  43. Williamkak's avatar Williamkak says:

    Being well-dressed is significant for building a personal image.
    A thoughtful appearance helps express personality.
    Stylish clothing can boost confidence.
    In everyday life, appearance often shapes first impressions.
    https://graph.org/Zara-01-12-2
    Balanced style choices make communication easier.
    It is important to consider one’s own comfort as well as the occasion.
    Fashion trends give people the chance to refresh their image.
    Ultimately, dressing stylishly helps people feel confident.

  44. Gordonnit's avatar Gordonnit says:

    I’ve been exploring https://terpenewarehouse.com/pages/what-are-the-side-effects-of-terpenes recently, and I’m deep down enjoying the experience. The scents are with, natural, and pleasant. They annex a discriminative touch to my day after day routine, dollop set the mood and atmosphere. A great hit upon quest of anyone who appreciates aromatic wellness tools.

  45. Winstongog's avatar Winstongog says:

    Health information is more accessible than ever before.Clarity is often missing despite abundance.Medical topics are often framed in oversimplified terms.Critical details are easily lost.Subtle changes are easily missed or misread.The problem stems from oversimplified framing.Physiological systems respond differently under similar conditions.Time plays a critical role in understanding.Attention allows patterns to become visible.Editorial discussion helps organize this complexity.Depth requires room to develop.Dialogue remains central.Thinking replaces instruction.It aligns with thoughtful health decision-making.For anyone ready to explore health responsibly.To gain deeper context and insight into iMedix medicine database.

Comments are closed.