dart-lang / mockito

Mockito-inspired mock library for Dart
https://pub.dev/packages/mockito
Apache License 2.0
623 stars 160 forks source link

Mocking a class which is created at runtime #743

Closed avdhootu27 closed 2 months ago

avdhootu27 commented 2 months ago

I am testing a widget where I need to create an object of a database class. I want to mock a method from that class, how can I mock it? I tried mocking it like:

@GenerateNiceMocks([MockSpec<MyDatabase>()])
import 'test.mocks.dart';

and I am using it as:

MockMyDatabase db = MockMyDatabase();
when(db.insertFolder(any)).thenAnswer((_) => Future.value(true));

But when I run the test it gives errors:

flutter: The following SqfliteFfiException was thrown running a test (but after the test had completed):
flutter: SqfliteFfiException(sqlite_error: 14, , open_failed: SqliteException(14): while opening the
flutter: database, unable to open database file, unable to open database file (code 14)})
flutter: DatabaseException(open_failed: SqliteException(14): while opening the database, unable to open
flutter: database file, unable to open database file (code 14))

It means it is not calling a mocked object, it is using a real object. So how can I mock that object which will be created at runtime (dynamically)?

yanok commented 2 months ago
  1. This is not a bug, right? Please don't file it as such then. Asking other Mockito users on forums such as stack overflow (or just searching the existing questions) might be more fruitful than bugging the Mockito developers.
  2. You created your mock and set an expectation, now you need to pass db to the code that uses MyDatabase, Mockito won't (and can't) do that for you.