Skip to content

Commit

Permalink
Added test for removing from many-to-many relationship with composite…
Browse files Browse the repository at this point in the history
… key
  • Loading branch information
bkoelman committed Aug 6, 2022
1 parent 02d19b5 commit 6825c83
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,7 @@ public sealed class Car : Identifiable<string?>

[HasOne]
public Dealership? Dealership { get; set; }

[HasMany]
public ISet<Dealership> PreviousDealerships { get; set; } = new HashSet<Dealership>();
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,9 @@ protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<Dealership>()
.HasMany(dealership => dealership.Inventory)
.WithOne(car => car.Dealership!);

builder.Entity<Car>()
.HasMany(car => car.PreviousDealerships)
.WithMany(dealership => dealership.SoldCars);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -508,4 +508,52 @@ public async Task Can_delete_resource()
carInDatabase.Should().BeNull();
});
}

[Fact]
public async Task Can_remove_from_ManyToMany_relationship()
{
// Arrange
Dealership existingDealership = _fakers.Dealership.Generate();
existingDealership.SoldCars = _fakers.Car.Generate(2).ToHashSet();

await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Car>();
dbContext.Dealerships.Add(existingDealership);
await dbContext.SaveChangesAsync();
});

var requestBody = new
{
data = new[]
{
new
{
type = "cars",
id = existingDealership.SoldCars.ElementAt(1).StringId
}
}
};

string route = $"/dealerships/{existingDealership.StringId}/relationships/soldCars";

// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody);

// Assert
httpResponse.ShouldHaveStatusCode(HttpStatusCode.NoContent);

responseDocument.Should().BeEmpty();

await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Dealership dealershipInDatabase = await dbContext.Dealerships.Include(dealership => dealership.SoldCars).FirstWithIdAsync(existingDealership.Id);
dealershipInDatabase.SoldCars.ShouldHaveCount(1);
dealershipInDatabase.SoldCars.Single().Id.Should().Be(existingDealership.SoldCars.ElementAt(0).Id);
List<Car> carsInDatabase = await dbContext.Cars.ToListAsync();
carsInDatabase.ShouldHaveCount(2);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,7 @@ public sealed class Dealership : Identifiable<int>

[HasMany]
public ISet<Car> Inventory { get; set; } = new HashSet<Car>();

[HasMany]
public ISet<Car> SoldCars { get; set; } = new HashSet<Car>();
}

0 comments on commit 6825c83

Please sign in to comment.