Flutter Mockito -模拟投掷异常

knpiaxh1  于 2023-06-22  发布在  Flutter
关注(0)|答案(2)|浏览(91)

刚开始在Flutter中使用Mockito:
我想模拟调用方法时抛出的异常。所以我这样做了:

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

但当预期它会抛出ArgumentError时:

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

我运行flutter测试,输出是测试失败,即使它声明它确实是一个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

我做错了什么?

brc7rcf0

brc7rcf01#

如果你需要模拟一个异常,这两种方法都可以工作:
1.模拟调用并为expect函数提供一个预期在执行后会抛出的函数(如果任何测试在expect函数之外抛出异常,Mockito似乎会自动失败):

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

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

1.如果这是一个异步调用,并且你在try-catch块上捕获异常并返回一些东西,你可以使用then.Answer

when(mockInstance.foo(input))
  .thenAnswer((_) => throw ArgumentError());

final a = await mockInstance.foo(input);

// assert
verify(...);
expect(...)

1.如果异常不是由mock抛出的:

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

du7egjpx2#

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

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

相关问题