Reader small image

You're reading from  The MVVM Pattern in .NET MAUI

Product typeBook
Published inNov 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781805125006
Edition1st Edition
Languages
Right arrow
Author (1)
Pieter Nijs
Pieter Nijs
author image
Pieter Nijs

Pieter Nijs is a .NET consultant at Xebia in Belgium, with a keen interest in mobile and cloud development. He's been instrumental in diverse projects, from vast healthcare and telecom systems to compact LOB apps. Now, Pieter's exploring AI's potential to enhance customer projects innovatively. Passionate about technology, he actively experiments and shares knowledge as a conference speaker and trainer. Pieter has been awarded the Microsoft MVP Award since 2017, reflecting his unwavering passion and expertise in serving the community.
Read more about Pieter Nijs

Right arrow

Unit Testing

Let’s dive into something critical: unit testing. Think of it as your safety net. It’s not just about knowing your app runs smoothly now, but ensuring that after every tweak, update, or overhaul, your app keeps on ticking without hiccups or unexpected surprises. Regression bugs? We’re looking at you! With MVVM and the right testing practices, we can effectively guard against these potential issues.

In this chapter, we’re going to tackle the following:

  • The importance of unit testing
  • Setting up a unit test project
  • Generating data with Bogus
  • Mocking dependencies with Moq
  • Testing MAUI-specific code

While we won’t be diving deep into the weeds (after all, the intricacies can vary widely depending on the tools you use), I’ll guide you using a set of tools I’m familiar with: xUnit, Bogus, AutoBogus, and Moq. These are my go-to building blocks, but let’s remember: the .NET ecosystem is vast...

Technical requirements

To ensure you’re in sync with the upcoming content, make your way to our GitHub repository: https://github.com/PacktPublishing/MVVM-pattern-.NET-MAUI/tree/main/Chapter13. Kick off with the materials in the Start folder. And remember – if you’re ever in need of a consolidated reference, the Finish folder holds the final, refined code at the chapter’s close.

The importance of unit testing

A lesson I learned the hard way forever transformed my stance on software development: never underestimate unit testing.

Years ago, I was part of a dedicated team crafting an ambitious app. Our expertise in C# and the platform was undeniable. Yet, we overlooked unit tests, placing our faith in manual testing and our Quality Assurance (QA) team. The end product was highly recognized and praised, but the journey was a tumultuous one. Feedback from QA often revealed bugs, making each code adjustment feel risky.

Nearing deadlines was synonymous with sleepless nights, hasty bug fixes, and a looming fear of regressions. Post-project, I collaborated with diverse developers and encountered a colleague profoundly devoted to test-driven development (TDD). It was a true eye-opener, not just for the essence of unit testing but also for the flaws in our previous design choices.

My evolving journey underscored the real benefits of unit tests:

  • Efficiency...

Setting up a unit test project

In this section, we will be walking through the steps of setting up a unit test project and creating a first test. We’ll be using xUnit in this section. We’re not going to get all tangled up in the tiny details of this specific library because there are tons of other awesome ones. No matter what you choose, the big takeaways should stick with you. So, without further ado, let’s dive in and start setting the stage for effective ViewModel testing!

Creating a unit test project

Let’s start by creating an xUnit Test project. In xUnit, one of the things I appreciate is its simplicity. Test classes and methods are just normal classes and methods, without the need for special base classes or complex setups. Here’s how:

  1. In the Solution Explorer in Visual Studio, right-click Solution ‘Recipes App’ and select Add | New Project….
  2. In the Add a new project dialog, type xunit in the search box...

Generating data with Bogus

While handpicked data has its place in unit tests, it often comes with inherent bias: because we’ve written the functionality that we want to test, we have a certain expectation about the format of the values being used. To combat this, many tests benefit from randomized or generated data, especially when the specific input matters less than the resulting outcome. Bogus is a powerful tool tailored for those moments when you need reliable, unbiased test data without the manual labor.

In this section, we’ll introduce Bogus and AutoBogus and explore some of its basic capabilities. However, it’s worth noting that we’re merely scratching the surface here. These tools offer many features, but for the sake of brevity and focus, we’ll keep our discussion high-level, touching only upon a few fundamental use cases.

Let’s start off by adding AutoBogus (and thus also Bogus) to our project:

  1. In Visual Studio, right...

Mocking dependencies with Moq

Testing frequently involves scenarios where our system under test interacts with external dependencies, whether they are databases, APIs, or other services. Running tests against these real dependencies can lead to slow, unpredictable outcomes and potentially unwanted side effects. Mocking provides a solution by simulating these dependencies, ensuring our tests focus purely on the component at hand. Through mocking, we gain control over external interactions, ensuring our tests are swift, reliable, and free from external influences.

Integration tests

When writing unit tests, we typically want to mock external dependencies as much as possible. However, it is often valuable to also test the integration of different components to ensure they work together seamlessly. This is where integration tests come in. Unlike unit tests, which focus heavily on mocking to test units in isolation, integration tests often involve fewer mocks. This ensures that components...

Testing MAUI-specific code

As shown in the previous examples, the majority of our code can be tested independently of the platform. But let’s not forget that there is code in our MAUI project as well that could benefit from some unit tests.

Let’s start by adding a new project to hold our tests for the Recipes.Mobile project:

  1. Add a new xUnit Test Project type, just as we did at the beginning of this chapter. Name this project Recipes.Mobile.UnitTests.
  2. Once the project has been created, add a reference to the Recipes.Mobile project.
  3. Add the AutoBogus NuGet package to this project.

The Recipes.Mobile.UnitTests project doesn’t target any specific frameworks other than net8.0. Because of that, we need to make sure net8.0 is on the list of target frameworks of the MAUI project as well. Also, we need to make sure that when the Recipes.Mobile project targets this additional net8.0 framework, it doesn’t output an EXE file. Let’s see...

Summary

In this chapter, we delved into unit testing within the MAUI framework, specifically focusing on testing ViewModels and some MAUI components. It’s worth noting that while we focused on these areas, the tools and techniques discussed are equally effective for testing services, repositories, and other integral parts of your application. Beyond just validating the code’s functionality, unit testing acts as a safety net, ensuring maintainability and robustness by reducing the chances of regression bugs. This powerful approach empowers us to iterate faster, removing the constant need for cumbersome deployments or manual checks. Leveraging mock implementations, we can seamlessly mimic and validate countless scenarios, and this validation remains ingrained in our code base. As we add or modify features, this ensures every intricate use case remains covered. A key takeaway is the significant portion of our app that can be tested independently of platform-specific details...

Further reading

To learn more about the topics that were covered in this chapter, take a look at the following resources:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
The MVVM Pattern in .NET MAUI
Published in: Nov 2023Publisher: PacktISBN-13: 9781805125006
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Pieter Nijs

Pieter Nijs is a .NET consultant at Xebia in Belgium, with a keen interest in mobile and cloud development. He's been instrumental in diverse projects, from vast healthcare and telecom systems to compact LOB apps. Now, Pieter's exploring AI's potential to enhance customer projects innovatively. Passionate about technology, he actively experiments and shares knowledge as a conference speaker and trainer. Pieter has been awarded the Microsoft MVP Award since 2017, reflecting his unwavering passion and expertise in serving the community.
Read more about Pieter Nijs