代码之家  ›  专栏  ›  技术社区  ›  xpeldev

颤振:测试是否引发特定异常

  •  2
  • xpeldev  · 技术社区  · 7 年前

    简言之 throwsA(anything) 对我来说,在dart中进行单元测试是不够的。如何测试一个 特定的错误消息或类型 ?

    class MyCustErr implements Exception {
      String term;
    
      String errMsg() => 'You have already added a container with the id 
      $term. Duplicates are not allowed';
    
      MyCustErr({this.term});
    }
    

    以下是通过的当前断言,但希望检查上面的错误类型:

    expect(() => operations.lookupOrderDetails(), throwsA(anything));

    这就是我想做的:

    expect(() => operations.lookupOrderDetails(), throwsA(MyCustErr));

    1 回复  |  直到 7 年前
        1
  •  34
  •   Ber    5 年前

    这应该满足您的要求:

    expect(() => operations.lookupOrderDetails(), throwsA(isA<MyCustErr>()));
    

    如果您只想检查异常,请检查此 answer :

        2
  •  14
  •   Ber    6 年前

    在`TypeMatcher<>'在颤振1.12.1中已被弃用,我发现这是可行的:

    expect(() => operations.lookupOrderDetails(), throwsA(isInstanceOf<MyCustErr>()));
    
        3
  •  9
  •   Brett Sutton    5 年前

    正确的方法

    import 'package:dcli/dcli.dart';
    import 'package:test/test.dart';
    
     /// GOOD: works in all circumstances.
     expect(() => restoreFile(file), throwsA(isA<RestoreFileException>()));
    

    一些例子表明:

    import 'package:dcli/dcli.dart';
    import 'package:test/test.dart';
     /// BAD: works but not in all circumstances
     expect(restoreFile(file), throwsA(isA<RestoreFileException>()));
    

    请注意缺少的“()=>”在期待之后。

    不同之处在于,第一种方法适用于返回void的函数,而第二种方法则不适用。

    因此,第一种方法应该是首选的技术。

    要测试特定错误消息,请执行以下操作:

    import 'package:dcli/dcli.dart';
    import 'package:test/test.dart';
    
        expect(
            () => copy(from, to),
            throwsA(predicate((e) =>
                e is CopyException &&
                e.message == 'The from file ${truepath(from)} does not exists.')));
    
        4
  •  1
  •   Rajat Arora    6 年前

    第一次导入正确的包 '包装:matcher/matcher.dart'

    expect(() => yourOperation.yourMethod(),
          throwsA(const TypeMatcher<YourException>()));
    
        5
  •  0
  •   Mihai Neagoe    6 年前

    如果有人想像我一样使用异步函数进行测试,您只需添加 async expect中的关键字,请记住 lookupOrderDetails 是一个异步函数:

    expect(() **async** => **await** operations.lookupOrderDetails(), throwsA(const TypeMatcher<MyCustErr>()));
    
    expect(() **async** => **await** operations.lookupOrderDetails(), isInstanceOf<MyCustErr>()));
    

    它仍然使用冈特的答案,这是非常好的!

        6
  •  0
  •   user8730776 user8730776    5 年前

    expect(operations.lookupOrderDetails, throwsA(isA<MyCustErr>()));`