Let's refactor a test: PaymentProxy
Tags: csharp, tutorial, dotnet, unittest
Published: 2024-03-18 05:00:00

_I originally posted this post on [my blog](https://canro91.github.io/2021/08/16/WriteCustomAssertions/). It's part of the [Unit Testing 101](https://canro91.github.io/UnitTesting) series. I updated it for accuracy and comprehensiveness._

Let's continue refactoring a test to make it more readable. In this post, let's learn a qick tip to write readable tests: using custom verification methods for mocks.

This time, let's say we have a payment processing system, and we want to provide our users a user-friendly client to call our endpoints.

We want to test that our `PaymentProxy` calls the right endpoints. For example, if we change the version number, our client uses that version number in the URLs.

These are the tests. Take a moment to see what you would refactor.

```csharp
[TestClass]
public class PaymentProxyTests
{
	[TestMethod]
	public async Task PayAsync_ByDefault_CallsLatestVersion()
	{
		var fakeClient = new Mock<IApiClient>();
		var proxy = new PaymentProxy(fakeClient.Object);

		await proxy.PayAsync(APaymentRequest);

		fakeClient
			.Verify(x => x.PostAsync<PaymentRequest, ApiResult>(
				It.Is<Uri>(t => t.AbsoluteUri.Contains("/v2/pay", StringComparison.InvariantCultureIgnoreCase)), It.IsAny<PaymentRequest>()),
				Times.Once);
	}

	[TestMethod]
	public async Task PayAsync_VersionNumber_CallsEndpointWithVersion()
	{
		var fakeClient = new Mock<IApiClient>();
		var proxy = new PaymentProxy(fakeClient.Object, Version.V1);

		await proxy.PayAsync(APaymentRequest);

		fakeClient
			.Verify(x => x.PostAsync<PaymentRequest, ApiResult>(
				It.Is<Uri>(t => t.AbsoluteUri.Contains("/v1/pay", StringComparison.InvariantCultureIgnoreCase)), It.IsAny<PaymentRequest>()),
				Times.Once);
	}

	private static PaymentRequest APaymentRequest
		=> new PaymentRequest
		{
			// All initializations here...
			Amount = new Amount
			{
				CurrencyCode = "USD",
				Value = 1_000
			}
		};
}
```

These tests use [Moq to write fake objects](https://canro91.github.io/2020/08/11/HowToCreateFakesWithMoq/) and [object mothers to create test data](https://canro91.github.io/2021/04/26/CreateTestValuesWithBuilders/).

Did you notice the `Verify()` methods in the two tests? And did you notice how buried inside that boilerplate is the URL we want to check? That's what we're interested in. All that noise!

## Create a custom Verify method

Let's create an extension method for our `fakeClient`: `VerifyUriContains()`. Something like this,

```csharp
using Moq;
using System;

namespace MyCoolExtensions;

public static class MockApiClientExtensions
{
	public static void VerifyUriContains(this Mock<IApiClient> fakeClient, string relativeUri)
	//                 👆👆👆
	{
		fakeClient
			.Verify(x => x.PostAsync<PaymentRequest, ApiResult>(
						It.Is<Uri>(t => t.AbsoluteUri.Contains(relativeUri, StringComparison.InvariantCultureIgnoreCase)),
						It.IsAny<PaymentRequest>()),
					Times.Once);
	}
}
```

With our `VerifyUriContains()` in place, let's refactor our tests to use it,

```csharp
[TestClass]
public class PaymentProxyTests
{
	[TestMethod]
	public async Task PayAsync_ByDefault_CallsLatestVersion()
	{
		var fakeClient = new Mock<IApiClient>();
		var proxy = new PaymentProxy(fakeClient.Object);

		await proxy.PayAsync(AnyPaymentRequest);

		fakeClient.VerifyUriContains("/v2/pay");
		//         👆👆👆
		// Now, it's way more readable
	}

	[TestMethod]
	public async Task PayAsync_VersionNumber_CallsEndpointWithVersion()
	{
		var fakeClient = new Mock<IApiClient>();
		var proxy = new PaymentProxy(fakeClient.Object, Version.V1);

		await proxy.PayAsync(AnyPaymentRequest);

		fakeClient.VerifyUriContains("/v1/pay");
		//         👆👆👆
		// No more boilerplate code to check things
	}

	private static PaymentRequest APaymentRequest
		=> new PaymentRequest
		{
			// All initializations here...
			Amount = new Amount
			{
				CurrencyCode = "USD",
				Value = 1_000
			}
		};
}
```

After this refactoring, our tests are more readable. And we wrote the tests in the same terms as our domain language. No more ceremony to check we called the right URL endpoints.

Voilà! A quick refactoring tip I use often. Let's write assertions using the same language as our domain model. We could write custom assertions with private methods and share them in a base class or extension methods on "result" objects.

***

_Hey, there! I'm Cesar, a software engineer and lifelong learner. If you want to upgrade your unit testing skills, check my course: [Mastering C# Unit Testing with Real-world Examples](https://www.udemy.com/course/mastering-csharp-unit-testing-with-real-world-examples/?referralCode=8456B1B78E2EDE923174) on Udemy. Practice with hands-on exercises and learn best practices by refactoring real-world unit tests._

{% cta https://www.udemy.com/course/mastering-csharp-unit-testing-with-real-world-examples/?referralCode=8456B1B78E2EDE923174 %} 🚀 Master C# Unit Testing with Real-world Examples {% endcta %}

_Happy testing!_