Flutter Mockito - Mock Throwing Exceptions Flutter Mockito - Mock Throwing Exceptions flutter flutter

Flutter Mockito - Mock Throwing Exceptions


I ran into the same problem. Try

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

Here is an example class with all tests passing

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


If you need to mock an exception, both of these approaches should work:

  1. Mock the call and provide the expect function with a function that is expected to throw once it's executed (Mockito seems to fail automatically if any test throws an exception outside expect function):

    when(mockInstance.foo(input))  .thenThrow(ArgumentError);expect(  () => mockInstance.foo(input), // or just mockInstance.foo(input)  throwsArgumentError,);
  2. In case it's an async call, and you are catching the exception on a try-catch block and returning something, you can use then.Answer :

    when(mockInstance.foo(input))  .thenAnswer((_) => throw ArgumentError());final a = await mockInstance.foo(input);// assertverify(...);expect(...)
  3. If the exception is not thrown by a mock:

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