Assertions in Dart and Flutter Tests: Numeric Matchers

Published on by Flutter News Hub

Assertions in Dart and Flutter Tests: Numeric Matchers

Testing numerical values in Flutter requires precise assertions to ensure accuracy. Flutter provides a set of range matchers that allow developers to assert whether a value falls within a specified range. In this article, we'll explore closeTo, inInclusiveRange, inExclusiveRange, inOpenClosedRange, and inClosedOpenRange with detailed explanations and examples.

closeTo

This matcher tests whether a value is within a certain range of another value. It takes two arguments: the expected value and the delta value. The delta value specifies the maximum difference between the actual and expected values. Here’s an example:

expect(2.0, closeTo(1.5, 0.5));

This assertion will pass because 2.0 is within 0.5 of 1.5.

inInclusiveRange

This matcher tests whether a value is within a range that includes both endpoints. It takes two arguments: the start and end of the range. Here’s an example:

expect(5, inInclusiveRange(1, 10));

This assertion will pass because 5 is within the range [1, 10].

inExclusiveRange

This matcher tests whether a value is within a range that excludes both endpoints. It takes two arguments: the start and end of the range. Here’s an example:

expect(5, inExclusiveRange(1, 10));

This assertion will fail because 5 is not within the range (1, 10).

inOpenClosedRange

This matcher tests whether a value is within a range that includes the start but excludes the end. It takes two arguments: the start and end of the range. Here’s an example:

expect(5, inOpenClosedRange(1, 5));

This assertion will pass because 5 is within the range [1, 5).

inClosedOpenRange

This matcher tests whether a value is within a range that excludes the start but includes the end. It takes two arguments: the start and end of the range. Here’s an example:

expect(5, inClosedOpenRange(5, 10));

This assertion will pass because 5 is within the range (5, 10].


Flutter News Hub