'In Dart, how to verify a void method that does not throw exception in unit tests?

I am implementing some data verification library in Dart. The validating method has void return type and throws exceptions on errors. The code below shows an example.

import 'package:quiver/check.dart';
    
void validate(int value) {
    checkArgument(value >= 0 && value <= 100);
}

In unit tests, I could use following code to test the exception case for invalid input:

expect(() => validate(-1), throwsArgumentError);

However, how to verify that the method does not throw exception for a valid input?



Solution 1:[1]

package:test provides a returnsNormally Matcher. You'd use it in the same way as the throwsA/etc. Matchers where it matches against a zero-argument function:

expect(() => validate(-1), returnsNormally);

Even though allowing your function to throw an uncaught exception ultimately would result in a failed test regardless, using returnsNormally can result in a clearer failure message.

For completeness (no pun intended), the equivalent for an asynchronous function would be to use the completes matcher:

await expectLater(someAsynchronousFunction(), completes);

Solution 2:[2]

Just call the method. If it does throw, then the test will fail.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 lrn