Just started using Mockito in Flutter:
I want to mock an exception being thrown when a method is called. So I did this:
when(mockInstance.foo(input).thenThrow(ArgumentError);
But then when expecting that it will throw an ArgumentError:
expect(mockInstance.foo(input), throwsArgumentError);
I run flutter test and the output is that the test failed even though it states that it is indeed an 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
What am I doing wrong?
If you need to mock an exception, both of these approaches should work:
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,
);
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);
// assert
verify(...);
expect(...)
If the exception is not thrown by a mock:
expect(
methodThatThrows()),
throwsA(isA<YourCustomException>()),
);
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With