【问题标题】:Flutter Mockito - Mock Throwing ExceptionsFlutter Mockito - 模拟抛出异常
【发布时间】:2019-07-25 02:13:42
【问题描述】:

刚开始在 Flutter 中使用 Mockito:

我想模拟调用方法时抛出的异常。所以我这样做了:

when(mockInstance.foo(input).thenThrow(ArgumentError);

但是当期望它会抛出一个 ArgumentError 时:

expect(mockInstance.foo(input), throwsArgumentError);

我运行颤振测试,输出是测试失败,即使它声明它确实是一个 ArgumentError:

 ArgumentError 
 package:mockito/src/mock.dart 346:7                             
 PostExpectation.thenThrow.<fn>
 package:mockito/src/mock.dart 123:37                            
 Mock.noSuchMethod
 package:-/--/---/Instance.dart 43:9  MockInstance.foo
 tests/Instance_test.dart 113:26 ensureArgumentErrorIsThrown

我做错了什么?

【问题讨论】:

    标签: unit-testing exception flutter mockito


    【解决方案1】:

    我遇到了同样的问题。试试

    expect(() => mockInstance.foo(input), throwsArgumentError);
    

    这是一个所有测试都通过的示例类

    import 'package:flutter_test/flutter_test.dart';
    import 'package:mockito/mockito.dart';
    
    void main() {
      test("",(){
        var mock = new MockA();
        when(mock.foo1()).thenThrow(new ArgumentError());
    
        expect(() => mock.foo1(), throwsArgumentError);
      });
    
      test("",(){
        var mock = new MockA();
        when(mock.foo2()).thenThrow(new ArgumentError());
    
        expect(() => mock.foo2(), throwsArgumentError);
      });
    
      test("",(){
        var mock = new MockA();
        when(mock.foo3()).thenThrow(new ArgumentError());
    
        expect(() => mock.foo3(), throwsArgumentError);
      });
    
      test("",(){
        var mock = new MockA();
        when(mock.foo4()).thenThrow(new ArgumentError());
    
        expect(() => mock.foo4(), throwsArgumentError);
      });
    }
    
    class MockA extends Mock implements A {}
    
    class A {
      void foo1() {}
      int foo2() => 3;
      Future foo3() async {}
      Future<int> foo4() async => Future.value(3);
    }
    

    【讨论】:

    • 你能解释一下为什么我们需要在expect(() =&gt; actual, matcher)中传递箭头函数吗?
    • 恐怕不能给你任何有效的解释。
    【解决方案2】:

    如果您需要模拟异常,这两种方法都应该有效:

    1. 模拟调用并为expect 函数提供一个函数,该函数一旦执行就会抛出(如果任何测试在expect 函数之外抛出异常,Mockito 似乎会自动失败):

      when(mockInstance.foo(input))
        .thenThrow(ArgumentError);
      
      expect(
        () => mockInstance.foo(input), // or just mockInstance.foo(input)
        throwsArgumentError,
      );
      
    2. 如果是异步调用,并且您在 try-catch 块上捕获异常并返回某些内容,则可以使用 then.Answer

      when(mockInstance.foo(input))
        .thenAnswer((_) => throw ArgumentError());
      
      final a = await mockInstance.foo(input);
      
      // assert
      verify(...);
      expect(...)
      
    3. 如果异常不是由 mock 抛出的:

      expect(
        methodThatThrows()),
        throwsA(isA<YourCustomException>()),
      );
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 2013-04-21
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 2011-04-15
      相关资源
      最近更新 更多