Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 898
Yun Huang Avatar asked Sep 01 '25 16:09

Yun Huang


2 Answers

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);
like image 117
jamesdlin Avatar answered Sep 04 '25 20:09

jamesdlin


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

like image 42
lrn Avatar answered Sep 04 '25 18:09

lrn