ucef
ucef

Reputation: 557

Assert duplicate element in unit testing

How can I to make a unit test check that a list of object not contains a duplicate element based on some properties.

Here is what I tried to do:

[Fact]
public void RecupererReferentielContactClient_CasNominal_ResultOk()
{
     // Arange
     var contactCoreService = Resolve<IContactCoreService>();
     int clientId = 56605;
     ICollection<Personne> listPersone = new List<Personne>();

     // Act
     WithUnitOfWork(() => listPersone = contactCoreService.RecupererReferentielDeContactClient(clientId));

      // Assert
     listPersone.ShouldSatisfyAllConditions(
            () => listPersone.ShouldNotBeNull(),
            () => listPersone.ShouldBeUnique());            
}

How can I make my unit test using shouldly?

Upvotes: 1

Views: 1401

Answers (2)

kkica
kkica

Reputation: 4104

Group by all the properties you want to check, and then test if all the groups have exactly 1 item.

bool allUnique= listPersone
    .GroupBy(p=> new {properties you want to check})
    .All(g=>g.Count()==1);
Assert.True(allUnique)

Edit:

You can also do

new HashSet(listPersone.Select(p=> new {properties you want to check} ))
.Should()
.HaveSameCount(listPersone);

Basically the hashset will contain the list of unique elements. If There are duplicate elements, only one will added to HashSet, therefore the HashSet will have a smaller count than listPersone.

Upvotes: 5

actual.GroupBy(k => k.Id).ShouldAllBe(item => item.Count() == 1);

will show a non-unique item, if assert failed

Upvotes: 0

Related Questions