1

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ucef
  • 557
  • 3
  • 10
  • 27

2 Answers2

5

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.

kkica
  • 4,034
  • 1
  • 20
  • 40
  • I have a constraint to do it with the framework shouldly but your solution do the job. thanks – ucef Feb 04 '20 at 09:33
0
actual.GroupBy(k => k.Id).ShouldAllBe(item => item.Count() == 1);

will show a non-unique item, if assert failed