DapperAutoData 1.0.6

There is a newer version of this package available.
See the version list below for details.
dotnet add package DapperAutoData --version 1.0.6                
NuGet\Install-Package DapperAutoData -Version 1.0.6                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DapperAutoData" Version="1.0.6" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add DapperAutoData --version 1.0.6                
#r "nuget: DapperAutoData, 1.0.6"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install DapperAutoData as a Cake Addin
#addin nuget:?package=DapperAutoData&version=1.0.6

// Install DapperAutoData as a Cake Tool
#tool nuget:?package=DapperAutoData&version=1.0.6                

Dapper Testing Library

This is a flexible, robust testing library that integrates a variety of powerful testing frameworks and tools. The library brings together AutoFixture, AutoMoq, Fluent Assertions, and Moq. It also includes a set of custom data generators for more targeted data generation and provides a pattern for adding new custom data generators.

Features

  • AutoFixture to generate anonymous data for your tests.
  • AutoMoq for automocking in your unit tests.
  • Fluent Assertions for more readable assertions.
  • Moq for manual mocking.
  • Custom Data Generators for generating specific types of data.

Installation

In package manager console run the command: Install-Package DapperAutoData

The library is distributed as a nuget package. After installing the package, the files DataGeneratorInstaller and AutoMoqDataAttribute.cs will be created.

The DataGeneratorInstaller will attempt to install any data generators in the assembly. A data generator is a class that implements the IDataGenerator interface.

How to Use

public class DapperDataCustomizations : IDapperProjectCustomization
{
    public void Customize(IFixture fixture)
    {
        fixture.RepeatCount = 3;
        fixture.Behaviors.Remove(new ThrowingRecursionBehavior());
        fixture.Behaviors.Add(new OmitOnRecursionBehavior());
    }
}

Customizing Data Generation

In some cases, you may want to customize how data is generated for your tests. You can do this by creating a class that implements the IDapperProjectCustomization interface and customizing the IFixture instance in the Customize method.

Here's an example of a class that customizes data generation:

In this example, DapperDataCustomizations customizes the IFixture instance in several ways:

  • It sets RepeatCount to 3, which means that collections generated by AutoFixture will contain 3 items.
  • It configures AutoMoq to set up all members on a mock to return a value.
  • It removes the ThrowingRecursionBehavior and adds the OmitOnRecursionBehavior, which changes how AutoFixture handles recursive structures.
  • It runs the DataGeneratorInstaller, which installs any data generators in the assembly.

You can add this class to your test project and it will automatically be used by the DapperAutoDataAttribute to customize data generation for your tests.

Creating a Data Generator

`public class AssistantGenerator : IDataGenerator { public void RegisterGenerators(IFixture fixture) { fixture.Register(() ⇒ GenerateAssistant(fixture)); }

private static Assistant GenerateAssistant(IFixture fixture) =>
    new()
    {
        ContactInfo = fixture.Create<ContactInfo>(),
        Name = Faker.Name.FullName()
    };

}`

Using Dapper Testing Library in your Tests

Here are some examples of tests using the Dapper Testing Library:

Example of a Unit Test

`[Theory] [DapperAutoData] public void Create_MinimumRequiredFields_NoValidationErrors(CreateAccountRequest request) { // Arrange

// Act
var account = new AccountEntity(request);

// Assert
account.Validate().Items.Should().BeNullOrEmpty();
account.LoginEmail.Should().Be(request.LoginEmail);
account.Address.Should().Be(request.Address);
account.ContactInfo.Should().Be(request.ContactInfo);

}`

Example of a Theory Driven Test

`[Theory] [DapperAutoData("")] [DapperAutoData(" ")] public void ChangeAddress_MissingCompany_ChangeSuccessful(string companyName, AccountEntity account, Address address) { // Arrange address.CompanyName = companyName;

// Act
var result = account.ChangeAddress(address);

// Assert
result.Items.Should().BeNullOrEmpty();
account.Address.Should().Be(address);

}`

Example of a Test with Injected Services in an Async Class

`[Theory] [DapperAutoData] public async Task CreateAsync_CreateDuplicateAccount_ReturnsDuplicateAccountErrorAsync( CreateAccountRequest request, [Frozen] Mock<IAccountRepo> repo, AccountService service ) { // Arrange repo.Setup(x ⇒ x.DoesEmailExistAsync(request.LoginEmail, It.IsAny<CancellationToken>())) .ReturnsAsync(true);

// Act
var response = await service.CreateAsync(request, CancellationToken.None);

// Assert
response.ErrorCode.Should().Be(ErrorCode.Duplicate);
response.IsSuccess.Should().BeFalse();
response.ErrorMessage.Should().Contain(BrokerResponse.DuplicateEmailError);

repo.Verify(x => x.CreateAsync(It.IsAny<AccountEntity>(), It.IsAny<CancellationToken>()), Times.Never);

}`

Testing for Exceptions

`[Theory] [DapperAutoData] public void Create_InvalidAccount_ThrowsException(CreateAccountRequest request) { // Arrange var service = new AccountService();

// Act
Action act = () => service.Create(request);

// Assert
act.Should().Throw<InvalidAccountException>();

}`

This will assert that calling the Create method with the provided request will throw an InvalidAccountException.

Customizing AutoFixture

In some cases, you may need to customize AutoFixture to create objects in a certain way. Here's an example of how you can do that:

csharpCopy code

public class CustomAutoDataAttribute : AutoDataAttribute { public CustomAutoDataAttribute() : base(() => new Fixture().Customize(new AutoMoqCustomization())) { } }

This creates a new AutoDataAttribute that you can use in your tests to create objects with AutoMoq. You can further customize this to fit your needs.

Extending the Library

The Dapper Testing Library is designed to be extensible. You can create your own data generators by implementing the IDataGenerator interface, and register them using the RegisterGenerators method. You can also customize the way that AutoFixture creates your objects, as shown in the example above.

Existing generator types

The Dapper Testing Library has a variety of built in types that can be used to specify ranges and types of auto data. These can generally be used interchangably with the types they are generating for, or you can grab the specific value from the .Value attribute.

  • FutureDateTimeOffset (DateTimeOffset)
  • PastDateTimeOffset (DateTimeOffset)
  • CompanyName (string)
  • NegativeNumber (int, double)
  • PositiveNumber (int, double)
  • PersonFirstName (string)
  • PersonFullName (string)
  • PersonLastName (string)
  • TestEmail (string)

Community

Feel free to submit issues and enhancement requests. Contributions are welcome!

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/myNewFeature)
  3. Commit your changes (git commit -m 'Add some feature')
  4. Push to the branch (git push origin feature/myNewFeature)
  5. Create a new Pull Request

Acknowledgements

We want to express our gratitude to all the projects that made this library possible.

License

Dapper Testing Library is released under the MIT License. See the bundled LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.10 125 5/6/2024
1.0.9 71 5/1/2024
1.0.8 83 4/26/2024
1.0.7 86 4/26/2024
1.0.6 86 4/26/2024
1.0.4 229 5/12/2023
1.0.3 160 5/12/2023
1.0.2 164 5/12/2023