Flutter Mockito-模拟投掷例外



刚刚开始在flutter中使用Mockito:

我想在调用方法时模拟一个例外。所以我这样做了:

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

,但是当期望它会引发一个参数时:

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

i进行扑打测试,输出是测试失败,即使它确实是一个参数:

 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

我在做什么错?

如果您需要模拟异常,这两种方法都应起作用:

  1. 模拟呼叫,并提供expect函数,其中有望在执行后将其投掷的函数(如果任何测试在expect函数之外抛出异常,Mockito似乎会自动失败):

    when(mockInstance.foo(input))
      .thenThrow(ArgumentError);
    expect(
      () => mockInstance.foo(input), // or just mockInstance.foo(input)
      throwsArgumentError,
    );
    
  2. 如果它是一个异步调用,并且您正在尝试键入块上并返回某些东西,则可以使用then.Answer

    when(mockInstance.foo(input))
      .thenAnswer((_) => throw ArgumentError());
    final a = await mockInstance.foo(input);
    // assert
    verify(...);
    expect(...)
    
  3. 如果未通过模拟抛出异常:

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

我遇到了相同的问题。尝试

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);
}

相关内容

  • 没有找到相关文章

最新更新