felangel / felangel/mocktail

`verify` verifies against wrong class when a second mock is called within the same `verify` call

Open
#179 1 comment 1 reaction 0 assignees View on GitHub
bug
Dominant language
Dart
Stars
702
Forks
88
PR merge metrics
No merged PRs in 30d

Description

This issue is best explained and demonstrated in code. There is a comment that explains the issue.

*Mocktail 0.3.0*

```dart
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';

class SomeDataProvider {
String getValue() => 'value';
}

class SomeClassToMockAndVerify {
void doSomethingImportant(String value) {}
}

class SubjectUnderTest {
final SomeDataProvider _someDataProvider;
final SomeClassToMockAndVerify _someClassToMockAndVerify;

SubjectUnderTest(this._someDataProvider, this._someClassToMockAndVerify);

void methodUnderTest() {
// You'll see what this is for later:
_someDataProvider.getValue();
_someDataProvider.getValue();
_someDataProvider.getValue();
_someDataProvider.getValue();
_someDataProvider.getValue();

_someClassToMockAndVerify.doSomethingImportant(
_someDataProvider.getValue(),
);
}
}

class MockSomeDataProvider extends Mock implements SomeDataProvider {}

class MockSomeClassToMockAndVerify extends Mock implements SomeClassToMockAndVerify {}

void main() {
test('bug example', () {
final mockSomeDataProvider = MockSomeDataProvider();
when(() => mockSomeDataProvider.getValue()).thenReturn('mock value');
final mockSomeClassToMockAndVerify = MockSomeClassToMockAndVerify();

final subjectUnderTest = SubjectUnderTest(
mockSomeDataProvider,
mockSomeClassToMockAndVerify,
);
subjectUnderTest.methodUnderTest();

verify(
() => mockSomeClassToMockAndVerify.doSomethingImportant(
// Whoops! Here we accidentally call a method of a *second* mock during a verify call. Now,
// the verification is broken, and is verifying `mockSomeDataProvider`'s calls instead of
// `mockSomeClassToMockAndVerify`'s calls!
// As evidence of this, the test fails saying there were 6 calls instead of 1.
// This is very confusing as a developer, since we're verifying `doSomethingImportant` and
// being told it was called 6 times when it was only called once.
// Of course, we should use the literal 'mock value' string here, but my ask is just that
// this scenario be better handled, perhaps with a special exception.
mockSomeDataProvider.getValue(),
),
).called(1);
// Expected: <1>
// Actual: <6>
// Unexpected number of calls
});
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.