Janus 1.0.0

Provides per-integration test database provisioning and database seeding for projects that utilize Entity Framework Core.

There is a newer prerelease version of this package available.
See the version list below for details.
Install-Package Janus -Version 1.0.0
dotnet add package Janus --version 1.0.0
<PackageReference Include="Janus" Version="1.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Janus --version 1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: Janus, 1.0.0"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. Copy this into the interactive tool or source code of the script to reference the package.
// Install Janus as a Cake Addin
#addin nuget:?package=Janus&version=1.0.0

// Install Janus as a Cake Tool
#tool nuget:?package=Janus&version=1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

Usage

Setting the stage for our example

In order to utilize the Jane API, you need to have a DbContext with some Entities and a API Controller created.

Provisioning a database

Our first Integration test will provision a database and make an Http Request to our API. The test will make sure we received a http status code of 200 OK.

[TestClass]
public class CreateDbContextTests
{
    private ApiIntegrationTestFactory<Startup> testFactory;

    [TestInitialize]
    public void Initialize() => this.testFactory = new ApiIntegrationTestFactory<Startup>();

    [TestCleanup]
    public void Cleanup() => this.testFactory.Dispose();

    [TestMethod]
    public async Task GetUsers_ReturnsOkStatusCode()
    {
        // Arrange - Sets up and creates the database.
        this.testFactory.WithDataContext<AppDbContext>("Default");
        var client = this.testFactory.CreateClient();

        // Act
        HttpResponseMessage response = await client.GetAsync("api/users");

        // Assert
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    }
}

Seeding the database

We can seed the database inline, within each test. This is the quickest and easiest approach.

[TestMethod]
public async Task GetUsers_ReturnsFakeUsers()
{
    // Arrange
    var users = new UserEntity[]
    {
         new UserEntity 
        {
            Address = this.dataFaker.Address.FullAddress(), 
            Email = this.dataFaker.Internet.Email(), 
            Username = this.dataFaker.Internet.UserName() 
        }, 
    };

    this.testFactory.WithDataContext<AppDbContext>("Default")
        .WithSeedData(context =>
        {
            context.Users.AddRange(users);
            context.SaveChanges();
        });

    var client = this.testFactory.CreateClient();

    // Act
    HttpResponseMessage response = await client.GetAsync("api/users");
    string responseBody = await response.Content.ReadAsStringAsync();
    UserEntity[] responseData = JsonConvert.DeserializeObject<UserEntity[]>(responseBody);

    // Assert
    Assert.AreEqual(users.Length, responseData.Length);
}

This uses the Bogus framework to produce fake data for each user, then the test inserts them into the DbContext for saving. When the Integration Test runs, we can now verify that our API is returning the data we just inserted into the database.

Entity Seeder

There are use-cases were you have more complex relationships though. Building those out inline within each test can be cumbersome. You can use the EntitySeeder API to make your seeding re-usable across tests and move the complex relationship building to live outside of your tests.

public class UserEntitySeeder : EntitySeeder<UserEntity>
{
    protected override bool MapEntities(UserEntity[] seededEntities, ISeedReader seedReader) => true;

    protected override IList<UserEntity> Seed(SeedOptions options)
    {
        IList<UserEntity> users = new Faker().Make(10, count =>
        {
            UserEntity user = new Faker<UserEntity>()
            .RuleFor(entity => entity.Address, faker => faker.Address.FullAddress())
            .RuleFor(entity => entity.Email, faker => faker.Internet.Email())
            .RuleFor(entity => entity.Id, Guid.NewGuid())
            .RuleFor(entity => entity.Username, faker => faker.Internet.UserName())
            .Ignore(entity => entity.Tasks);

            return user;
        });

        return users;
    }
}

public class TaskEntitySeeder : EntitySeeder<TaskEntity>
{
    protected override bool MapEntities(TaskEntity[] seededEntities, ISeedReader seedReader)
    {
        UserEntity[] users = seedReader.GetDataForEntity<UserEntity>();
        var faker = new Faker();

        foreach(TaskEntity task in seededEntities)
        {
            UserEntity user = faker.PickRandom(users);
            user.Tasks.Add(task);
            task.UserId = user.Id;
        }

        return true;
    }

    protected override IList<TaskEntity> Seed(SeedOptions options)
    {
        IList<TaskEntity> tasks = new Faker().Make(100, count =>
        {
            TaskEntity task = new Faker<TaskEntity>()
                .RuleFor(entity => entity.DueDate, faker => faker.Date.Soon())
                .RuleFor(entity => entity.Id, Guid.NewGuid())
                .RuleFor(entity => entity.Title, faker => faker.Random.String())
                .Ignore(entity => entity.UserId);

            return task;
        });

        return tasks;
    }
}

You can see in the TaskEntitySeeder that we ask the ISeedReader to provide us all of the seeded Users so we can build our relationships. This allows Entity Framework to save the seeded data easily, relationships and all. You can see from our example code that the TaskEntitySeeder will insert 100 records while the UserEntitySeeder will insert 10 records.

Your integration tests don't change very much. Instead of passing a callback to the WithSeedData method, you provide a generic Type representing your seed data.

[TestMethod]
public async Task GetUsers_ReturnsSeederData()
{
    // Arrange
    this.testFactory.WithDataContext<AppDbContext>("Default")
        .WithSeedData<UserEntitySeeder>()
        .WithSeedData<TaskEntitySeeder>();

    var client = testFactory.CreateClient();
    IEntitySeeder userSeeder = testFactory.GetDataContextSeedData<AppDbContext, UserEntitySeeder>();

    // Act
    HttpResponseMessage response = await client.GetAsync("api/users");
    string responseBody = await response.Content.ReadAsStringAsync();
    UserEntity[] responseData = JsonConvert.DeserializeObject<UserEntity[]>(responseBody);


    // Assert
    Assert.AreEqual(userSeeder.GetSeedData().Length, responseData.Length);
}

We can fetch the data we seeded, after the database has been created, and use that to verify that our API is still sending us back the right data.

Usage

Setting the stage for our example

In order to utilize the Jane API, you need to have a DbContext with some Entities and a API Controller created.

Provisioning a database

Our first Integration test will provision a database and make an Http Request to our API. The test will make sure we received a http status code of 200 OK.

[TestClass]
public class CreateDbContextTests
{
    private ApiIntegrationTestFactory<Startup> testFactory;

    [TestInitialize]
    public void Initialize() => this.testFactory = new ApiIntegrationTestFactory<Startup>();

    [TestCleanup]
    public void Cleanup() => this.testFactory.Dispose();

    [TestMethod]
    public async Task GetUsers_ReturnsOkStatusCode()
    {
        // Arrange - Sets up and creates the database.
        this.testFactory.WithDataContext<AppDbContext>("Default");
        var client = this.testFactory.CreateClient();

        // Act
        HttpResponseMessage response = await client.GetAsync("api/users");

        // Assert
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    }
}

Seeding the database

We can seed the database inline, within each test. This is the quickest and easiest approach.

[TestMethod]
public async Task GetUsers_ReturnsFakeUsers()
{
    // Arrange
    var users = new UserEntity[]
    {
         new UserEntity 
        {
            Address = this.dataFaker.Address.FullAddress(), 
            Email = this.dataFaker.Internet.Email(), 
            Username = this.dataFaker.Internet.UserName() 
        }, 
    };

    this.testFactory.WithDataContext<AppDbContext>("Default")
        .WithSeedData(context =>
        {
            context.Users.AddRange(users);
            context.SaveChanges();
        });

    var client = this.testFactory.CreateClient();

    // Act
    HttpResponseMessage response = await client.GetAsync("api/users");
    string responseBody = await response.Content.ReadAsStringAsync();
    UserEntity[] responseData = JsonConvert.DeserializeObject<UserEntity[]>(responseBody);

    // Assert
    Assert.AreEqual(users.Length, responseData.Length);
}

This uses the Bogus framework to produce fake data for each user, then the test inserts them into the DbContext for saving. When the Integration Test runs, we can now verify that our API is returning the data we just inserted into the database.

Entity Seeder

There are use-cases were you have more complex relationships though. Building those out inline within each test can be cumbersome. You can use the EntitySeeder API to make your seeding re-usable across tests and move the complex relationship building to live outside of your tests.

public class UserEntitySeeder : EntitySeeder<UserEntity>
{
    protected override bool MapEntities(UserEntity[] seededEntities, ISeedReader seedReader) => true;

    protected override IList<UserEntity> Seed(SeedOptions options)
    {
        IList<UserEntity> users = new Faker().Make(10, count =>
        {
            UserEntity user = new Faker<UserEntity>()
            .RuleFor(entity => entity.Address, faker => faker.Address.FullAddress())
            .RuleFor(entity => entity.Email, faker => faker.Internet.Email())
            .RuleFor(entity => entity.Id, Guid.NewGuid())
            .RuleFor(entity => entity.Username, faker => faker.Internet.UserName())
            .Ignore(entity => entity.Tasks);

            return user;
        });

        return users;
    }
}

public class TaskEntitySeeder : EntitySeeder<TaskEntity>
{
    protected override bool MapEntities(TaskEntity[] seededEntities, ISeedReader seedReader)
    {
        UserEntity[] users = seedReader.GetDataForEntity<UserEntity>();
        var faker = new Faker();

        foreach(TaskEntity task in seededEntities)
        {
            UserEntity user = faker.PickRandom(users);
            user.Tasks.Add(task);
            task.UserId = user.Id;
        }

        return true;
    }

    protected override IList<TaskEntity> Seed(SeedOptions options)
    {
        IList<TaskEntity> tasks = new Faker().Make(100, count =>
        {
            TaskEntity task = new Faker<TaskEntity>()
                .RuleFor(entity => entity.DueDate, faker => faker.Date.Soon())
                .RuleFor(entity => entity.Id, Guid.NewGuid())
                .RuleFor(entity => entity.Title, faker => faker.Random.String())
                .Ignore(entity => entity.UserId);

            return task;
        });

        return tasks;
    }
}

You can see in the TaskEntitySeeder that we ask the ISeedReader to provide us all of the seeded Users so we can build our relationships. This allows Entity Framework to save the seeded data easily, relationships and all. You can see from our example code that the TaskEntitySeeder will insert 100 records while the UserEntitySeeder will insert 10 records.

Your integration tests don't change very much. Instead of passing a callback to the WithSeedData method, you provide a generic Type representing your seed data.

[TestMethod]
public async Task GetUsers_ReturnsSeederData()
{
    // Arrange
    this.testFactory.WithDataContext<AppDbContext>("Default")
        .WithSeedData<UserEntitySeeder>()
        .WithSeedData<TaskEntitySeeder>();

    var client = testFactory.CreateClient();
    IEntitySeeder userSeeder = testFactory.GetDataContextSeedData<AppDbContext, UserEntitySeeder>();

    // Act
    HttpResponseMessage response = await client.GetAsync("api/users");
    string responseBody = await response.Content.ReadAsStringAsync();
    UserEntity[] responseData = JsonConvert.DeserializeObject<UserEntity[]>(responseBody);


    // Assert
    Assert.AreEqual(userSeeder.GetSeedData().Length, responseData.Length);
}

We can fetch the data we seeded, after the database has been created, and use that to verify that our API is still sending us back the right data.

Release Notes

Provides the initial set of APIs for seeding databases and seeding them for projects that utilize Entity Framework Core

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version History

Version Downloads Last updated
1.1.0-preview1 264 6/15/2019
1.0.0 403 6/10/2019
1.0.0-beta-1.0 181 6/9/2019