Janus 1.0.0

.NET Standard 2.0
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Janus --version 1.0.0
NuGet\Install-Package Janus -Version 1.0.0
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="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
#r "nuget: Janus, 1.0.0"
#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 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

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.

Product Versions
.NET net5.0 net5.0-windows net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows net7.0 net7.0-android net7.0-ios net7.0-maccatalyst net7.0-macos net7.0-tvos net7.0-windows
.NET Core netcoreapp2.0 netcoreapp2.1 netcoreapp2.2 netcoreapp3.0 netcoreapp3.1
.NET Standard netstandard2.0 netstandard2.1
.NET Framework net461 net462 net463 net47 net471 net472 net48 net481
MonoAndroid monoandroid
MonoMac monomac
MonoTouch monotouch
Tizen tizen40 tizen60
Xamarin.iOS xamarinios
Xamarin.Mac xamarinmac
Xamarin.TVOS xamarintvos
Xamarin.WatchOS xamarinwatchos
Compatible target framework(s)
Additional computed target framework(s)
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.1.0-preview1 392 6/15/2019
1.0.0 770 6/10/2019
1.0.0-beta-1.0 280 6/9/2019

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