Why does verify(() => mockObject.someGetter) throw 'Used on a non-mockito object' even though the object is a Mock?

Why does verify(() => mockObject.someGetter) throw 'Used on a non-mockito object' even though the object is a Mock?
typescript
Ethan Jackson

I'm currently writing unit tests for a Flutter app using mockito, and I'm running into an issue with verifying a getter call using the latest version of mockito (v5.x).

Here's my test setup:

@GenerateMocks([InternetConnectionChecker]) void main() { late MockInternetConnectionChecker internetConnectionChecker; late NetworkInfoImpl networkInfo; setUp(() { internetConnectionChecker = MockInternetConnectionChecker(); networkInfo = NetworkInfoImpl(internetConnectionChecker); }); test('should check internet connection', () async { // Arrange when(() => internetConnectionChecker.hasConnection) .thenAnswer((_) async => true); // Act final result = await networkInfo.isConnect; // Assert verify(() => internetConnectionChecker.hasConnection); // ❌ Throws error expect(result, true); }); }

error test mockito

Even though internetConnectionChecker is clearly a MockInternetConnectionChecker, the test throws this error:

Used on a non-mockito object package:matcher fail package:mockito/src/mock.dart 1155:7 _makeVerify.<fn> test\core\network\network_info_test.dart 30:13 main.<fn>.<fn>

However, if I write it like this, it works:

verify(internetConnectionChecker.hasConnection); // ✅ Works, but discouraged?

enter image description here From what I understand, using verify(() => ...) is the recommended way to ensure that the method or getter was actually called. So why does this error happen?

  • Ran flutter pub run build_runner build --delete-conflicting-outputs

  • Verified that the correct imports are used: package:mockito/mockito.dart

  • Confirmed the type via print(internetConnectionChecker.runtimeType)MockInternetConnectionChecker

Is there something special about getters in the latest versions of mockito? Or has there been a breaking change that I missed?

Answer

This error usualy means that the object you're verifying is not a Mockito mock.

To fix it, make sure the objec you're calling `verify()` on is created using `Mockito.mock()` or annotated with `@Mock`.

Example:

java SomeClass someObject = mock(SomeClass.class); verify(someObject).getSomething();

If someObject is not a mock Mockito can't track method calls thats why youre getting the exception.

Hope this helps Ive seen this issue come up when acidentally mixing real and mock objects in tets.

Related Articles