3

I am writing unit test using fluent-assertions and sqlite which stores badly decimal type.

I would like ALL my decimal comparison to ignore the floating part.

Is there a way to do it ?

Thanks !

Hayden
  • 2,902
  • 2
  • 15
  • 29
Jonathan ANTOINE
  • 9,021
  • 1
  • 23
  • 33

2 Answers2

4

FluentAssertions allows for approximation assertions for decimal / floating point numeric values.

The following method is specifically designed for floating point or decimal variables.

float value = 3.1415927F;
value.Should().BeApproximately(3.14F, 0.01F);

This will verify that the value of the float is between 3.139 and 3.141.

Reference FluentAssertions Documentation: Numeric types and everything else that implements IComparable<T>

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • 1
    Thanks for your answer, but I want that *ALL* my assertions on decimal types uses this precision settings. Is there a way to do it ? – Jonathan ANTOINE Aug 08 '19 at 06:45
1

As Nkosi pointed out we can use BeApproximately. Combine with Using and WhenTypeIs to apply it to all decimals within an object graph:

public class Foo
{
    public decimal Value1 { get; set; }
    public decimal Value2 { get; set; }
}

var fooActual = new Foo { Value1 = 1.001M, Value2 = 2.002M };
var fooExpected = new Foo { Value1 = 1.003M, Value2 = 2.005M };

fooActual.Should().BeEquivalentTo(
    fooExpected,
    options => options
        .Using<decimal>(ctx => ctx.Subject.Should().BeApproximately(ctx.Expectation, 0.01M))
        .WhenTypeIs<decimal>()
)
Russop
  • 36
  • 3