Generators

Often, we need to create some test data that we will use in multiple tests, like a test user, or we need to create multiple test users and keep track so that we can dispose of them once tests are complete.

This is why we use generators to keep track of all created entities in a list, maybe keep track of last created object, and in similar situations where we can iterate through that list and eventually dispose of created objects.

Generators section

We use generators in SetupFixtures for different tests, where we can create test data in OneTimeSetup method, and dispose of this test data in OneTimeTeardown method when all tests finish executing.

Here is a snippet of how UserGenerator is used in UserSetupFixture

[SetUpFixture]
[Parallelizable(ParallelScope.Fixtures)]
public class UserSetupFixture
{
    public DriverService DriverService { get; } = new DriverService();

    [OneTimeSetUp]
    public void Init()
    {
        DriverService.CreateOrReuseDriver();
        try
        {
            CreateTestData(UserGenerator.GenerateTestUser());
        }
        catch (Exception e)
        {
            UserGenerator.TestUser.Delete();
            Cleanup();

            throw new Exception("Failed to create test data for users feature testing", e);
        }
    }

    [OneTimeTearDown]
    public void UserFixtureTearDown()
    {
        if (UserGenerator.Users.Any())
        {
            DriverService.CreateOrReuseDriver();
            try
            {
                UserGenerator.Users.ForEach(u => DeleteUser(u.Identifier));
            }
            catch (Exception e)
            {
                throw new Exception("User cleanup failed.", e);
            }
            finally
            {
                Cleanup();
            }
        }
    }
}

Last updated

Was this helpful?