# Fluent Assertions 数字类型 和 IComparable 的断言

整型 int long, decimal 的断言

int theInt = 5;
theInt.Should().BeGreaterOrEqualTo(5); // >=
theInt.Should().BeGreaterOrEqualTo(3); // >=
theInt.Should().BeGreaterThan(4); // >
theInt.Should().BeLessOrEqualTo(5); // <=
theInt.Should().BeLessThan(6); // <
theInt.Should().BePositive(); // 正数
theInt.Should().Be(5); 
theInt.Should().NotBe(10);
theInt.Should().BeInRange(1, 10); //在范围内 1 到10 内含1和10 
theInt.Should().NotBeInRange(6, 10);
theInt.Should().Match(x => x % 2 == 1);

theInt = 0;
//theInt.Should().BePositive(); => Expected positive value, but found 0
//theInt.Should().BeNegative(); => Expected negative value, but found 0

theInt = -8;
theInt.Should().BeNegative(); //负数
int? nullableInt = 3;
nullableInt.Should().Be(3);

double theDouble = 5.1;
theDouble.Should().BeGreaterThan(5); //必须大于5
byte theByte = 2;
theByte.Should().Be(2); //必须是 2

theInt.Should().BeOneOf(new[] { 3, 6});

float double 类型 断言

请注意,Should().Be() 和 Should().NotBe() 不适用于浮点数(float)和双精度数(double)。 计算机表示浮点数(float或double类型)都有一个精度限制,对于超出了精度限制的浮点数,计算机会把它们的精度之外的小数部分截断。因此,本来不相等的两个浮点数在计算机中可能就变成相等的了。 永远不应该比较是否相等。 (写代码的地方也应该用 abs(f1,f2) < 0.000001)的方式来比较。 相反,使用 Should().BeInRange() 方法或以下专为浮点或十进制变量设计的方法。

float value = 3.1415927F;
value.Should().BeApproximately(3.14F, 0.01F); // 接近于 3.14
最近更新的
...