How do you unittest exceptions in Dart?

后端 未结 6 695
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 00:58

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

List range(start, stop) {
    i         


        
6条回答
  •  误落风尘
    2020-12-09 01:47

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

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

    to test that the right type of exception is raised:

    there are several predefined matchers for general purposes like throwsArgumentError, throwsRangeError, throwsUnsupportedError, etc.. for types for which no predefined matcher exists, you can use TypeMatcher.

    expect(() => range(5, 2), throwsA(TypeMatcher()));
    

    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).

提交回复
热议问题