Flutter Mockito-模拟抛出异常

时间:2019-03-03 17:49:21

标签: unit-testing exception flutter mockito

刚开始在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

我在做什么错了?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

如果您需要模拟异常,则这两种方法都可以使用:

  1. 模拟调用并为int main() { HANDLE t_thread = CreateThread(NULL, 0, ThreadRoutine, NULL, 0, NULL); if (t_thread ) { // Optionally do stuff, such as wait on the thread or ... /*After some time lets kill or terminate the thread we have created*/ BOOL re_term =TerminateThread(t_thread , DWORD dwExitCode); if(re_term == 0){ //failed /*maybe you should call GetLastError function*/ } else{ /*killed successefully*/ } } return 0; } 函数提供一个有望在执行后抛出的函数(如果任何测试在expect函数之外引发异常,则Mockito似乎会自动失败):

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

    then.Answer
  3. 如果模拟未引发异常:

    when(mockInstance.foo(input))
      .thenAnswer((_) => throw ArgumentError());
    
    final a = await mockInstance.foo(input);
    
    // assert
    verify(...);
    expect(...)