lebber
lebber

Reputation: 119

C# Entity Framework XUnit Tests Always Failing

I'm currently trying to setup some tests to check that my code is working. I've managed to set it up with the .NET 6 minimal API and use a test db context instead, however, when I have multiple tests all the tests are failing.

I believe the reason for this is because they are running parallel which is obviously causing a conflict with the database context.

To counteract this, I've tried an in memory database and create a new database based on a guid which is resolved before the test, however, I've read that in memory databases aren't the best for testing as it's not a true reflection. So I've opted to use a test SQL Server. Which I plan on tearing down after each test - I know this may take a lot longer than usual but I'm happy to take that given it's an accurate reflection of the code interacting with the database.

However, for that I think I need to run the tests individually rather than in parallel.

My test is really simple, it just tests a 200 and a count. Running them individually works perfectly.

public class GetUserEndpointTest()
{
  [Fact]
  public async Task OnSuccess_ReturnStatusCodeOk()
  {
    await using var application = new Application();
    var client = application.CreateClient();

    var response = await client.GetAsync("/v1/users");
    response.EnsureSuccessStatusCode();
  }

  [Fact]
  public async Task OnSuccess_ReturnsTheCorrectUserCount()
  {
    await using var application = new Application();
    var client = application.CreateClient();

    var users = await client.GetFromJsonAsync<List<User>>("/v1/users");
    users.Count.Shound().Be(1);
  }  
}

My application factory is just simple:

class Application : WebApplicationFactory<Program>
{
  protected override IHost CreateHost(IHostBuilder builder)
  {
    builder.ConfigureServices(services =>
    {
      services.RemoveAll(typeof(DbContextOptions<ApplicationContext>));
      services.AddDbContext<ApplicationContext>(options =>
        {
          options.UseSqlServer(
            "Server=localhost;Database=testing_database;Trusted_Connection=True;"
          );
        });
     });

     return base.CreateHost(builder);
  }
}

Upvotes: 0

Views: 1021

Answers (1)

Christopher Hamkins
Christopher Hamkins

Reputation: 1639

When testing with XUnit, you can prevent parallel execution of the tests by putting them in a "collection". You declare which tests belong to the collection by "decorating" the class declaration with a Collection attribute.

This is explained at https://xunit.net/docs/running-tests-in-parallel

For example:

    [Collection("NonParallelTestCollection")]
    public class MyUnitTests1
    {
    // your tests here ...
    }

    [Collection("NonParallelTestCollection")]
    public class MyUnitTests2
    {
    // your tests here ...
    }

In this example, none of the tests in either of the classes will run in parallel.

Upvotes: 1

Related Questions