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?
package:test
provides a returnsNormally
Matcher
. You'd use it in the same way as the throwsA
/etc. Matcher
s 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);
Just call the method. If it does throw, then the test will fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With