1

I am trying to test my collection using :

  var costByFactoryt = dataAccess.GetcostPerFactoryt(null, null);
  costByFactoryt.Count().Should().BeGreaterThan(0);
  costByFactoryt.Select(x => x.Cost.Should().BeGreaterThan(100));

But the problem is , if I change the last line of code to,

 costByFactoryt.Select(x => x.Cost.Should().BeGreaterThan(1000));

or

costingByCircuit.Select(x => x.Cost.Should().BeLessThan(100));

It still pass , which is wrong.

What I am trying to test is , all cost should be greater than 100.

Simsons
  • 12,295
  • 42
  • 153
  • 269

2 Answers2

5

It simply doesn't work that way because LINQ Select doesn't iterate the collection => your test code is not executed

According to Fluent Assertions documentation

The correct syntax should be

costingByCircuit.Select(x => x.Cost).Should().OnlyContain(x => x > 100);
Kien Chu
  • 4,735
  • 1
  • 17
  • 31
  • OP wants to test all items in the list to be greater than 100 with `FluentAssertions` – Kien Chu May 07 '18 at 07:00
  • because the `FluentAssertions` and `LINQ` is designed such way, **LINQ Select** don't iterate the collection, hence the test code is not executed – Kien Chu May 07 '18 at 07:42
  • Can you kindly add it to the answer, even you answer provide solution it lack of explanation. – Fabio May 07 '18 at 07:43
  • Updated @Fabio, also added the reference link to the official documentation – Kien Chu May 07 '18 at 07:46
3

Then problem with writing costByFactoryt.Select(x => x.Cost.Should().BeGreaterThan(100)); is that it tests nothing. It creates a lazy LINQ expression, which is never iterated, i.e. none of the BeGreaterThan are invoked.

When using Fluent Assertions, you will get the most detailed failure messages you avoid using Select as more information is then available to the failure message generator.

When

costByFactoryt.Select(x => x.Cost).Should().OnlyContain(x => x > 100)

fails, the message generator will output the Cost objects.

By instead writing

costByFactoryt.Should().OnlyContain(x => x.Cost > 100)

the failure message will the contain all the x objects instead.

Jonas Nyrup
  • 2,376
  • 18
  • 25