Janus 1.0.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 Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  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 was computed.  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 was computed.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos 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.1.0-preview1 520 6/15/2019
1.0.0 1,111 6/10/2019
1.0.0-beta-1.0 332 6/9/2019

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