Skip to content

A simple .NET library that verifies constructors and methods have guards in place against null arguments.

License

Notifications You must be signed in to change notification settings

rent-a-developer/ArgumentNullGuards

Repository files navigation

NuGet Version Quality Gate Status license semver

image icon ArgumentNullGuards

A simple .NET library that verifies constructors and methods have guards in place against null arguments.

Inspired by a brilliant idea from Thomas Levesque, see https://thomaslevesque.com/2019/11/19/easy-unit-testing-of-null-argument-validation-c-8-edition/.

Table of contents

Installation

First, install NuGet.

Then install the NuGet package from the package manager console:

PM> Install-Package RentADeveloper.ArgumentNullGuards

Quick start

Use the ArgumentNullGuardVerifier class to verify that your constructors and methods properly guard against null arguments.
Call the Verify method, passing in a lambda expression that invokes the constructor or method you want to test with valid (non-null) arguments.

If any argument is not properly guarded against null, an exception will be thrown, causing the test to fail.
If an ArgumentNullException is thrown, but with the wrong parameter name, the test will also fail.

using static RentADeveloper.ArgumentNullGuards;

class UserService
{
	private readonly IUserRepository userRepository;
	
	public UserService(IUserRepository userRepository)
	{
		ArgumentNullException.ThrowIfNull(userRepository);
		this.userRepository = userRepository;
	}

	public IUserPermission[] GetPermissions(User user)
	{
		ArgumentNullException.ThrowIfNull(user);
		...
	}
}

public class UserServiceTests
{
	[Fact]
	public void VerifyNullArgumentGuards()
	{
		var userRepository = Substitute.For<IUserRepository>();
		var user = Substitute.For<User>();

		ArgumentNullGuardVerifier.Verify(() => new UserService(userRepository));
		
		var instance = new UserService(userRepository);

		ArgumentNullGuardVerifier.Verify(() => instance.GetPermissions(user));
	}
}

Contributing

Contributions and bug reports are welcome and appreciated.
Please follow the repository's CONTRIBUTING.md and code style.
Open a GitHub issue for problems or a pull request with tests and a clear description of changes.

License

This library is licensed under the MIT license.

Documentation

Full API documentation is available here.

Change Log

The change log is available here.

Contributors

About

A simple .NET library that verifies constructors and methods have guards in place against null arguments.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages