How do you unittest exceptions in Dart?

2019-02-08 15:40发布

问题:

Consider a function that does some exception handling based on the arguments passed:

List range(start, stop) {
    if (start >= stop) {
      throw new ArgumentError("start must be less than stop");
    }
    // remainder of function
}

How do I test that the right kind of exception is raised?

回答1:

In this case, there are various ways to test the exception. To simply test that an exception is raised:

expect(() => range(5, 5), throws);

to test that the right type of exception is raised:

expect(() => range(5, 2), throwsA(new isInstanceOf<ArgumentError>()));

to ensure that no exception is raised:

expect(() => range(5, 10), returnsNormally);

to test the exception type and exception message:

expect(() => range(5, 3), 
    throwsA(predicate((e) => e is ArgumentError && e.message == 'start must be less than stop')));

here is another way to do this:

expect(() => range(5, 3), 
  throwsA(allOf(isArgumentError, predicate((e) => e.message == 'start must be less than stop'))));

(Thanks to Graham Wheeler at Google for the last 2 solutions).



回答2:

I like this approach:

test('when start > stop', () {
  try {
    range(5, 3);
  } on ArgumentError catch(e) {
    expect(e.message, 'start must be less than stop');
    return;
  }
  throw new ExpectException("Expected ArgumentError");  
});


回答3:

For simple exception testing, I prefer to use the static method API:

Expect.throws(
  // test condition
  (){ 
    throw new Exception('code I expect to throw');
  },
  // exception object inspection
  (err) => err is Exception
);


标签: dart