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/.
First, install NuGet.
Then install the NuGet package from the package manager console:
PM> Install-Package RentADeveloper.ArgumentNullGuardsUse 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));
}
}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.
This library is licensed under the MIT license.
Full API documentation is available here.
The change log is available here.
- David Liebeherr (info@rent-a-developer.de)