felangel / mocktail

A mock library for Dart inspired by mockito
https://pub.dev/packages/mocktail
MIT License
617 stars 81 forks source link

Error: Was a real method called, or perhaps an extension method? #48

Closed shinayser closed 3 years ago

shinayser commented 3 years ago

Hello folks its me again! After our talk about creating an extensions library (https://github.com/felangel/mocktail/pull/46) I started the project and faced the first problem of this approach: I moved the extension function to inside my project like that:

extension VoidAnswer on When<Future<void>> {
  /// Store a function which is called when this method stub is called.
  ///
  /// The function will be called and completed normally.
  void thenAnswerWithVoid() => thenAnswer((_) => Future<void>.value());

  //void thenAnswerWithVoid() => _completeWhen((_) => Future<void>.value());
}

Please note that I had to change the call as it was in the PR, because the method _completeAnswer is private in mocktail, so we can't call it directly.

void _completeWhen(Answer<T> answer) {
    if (_whenCall == null) {
      throw StateError(
        'No method stub was called from within `when()`. Was a real method '
        'called, or perhaps an extension method?',
      );
    }
    _whenCall!._setExpected<T>(answer);
    _whenCall = null;
    _whenInProgress = false;
  }

It throws Bad state: No method stub was called from within `when()`. Was a real method called, or perhaps an extension method?

Is there any workaround can you folks can think to overcome that issue?

felangel commented 3 years ago

Hi @shinayser 👋 Thanks for opening an issue!

The following works for me:

import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';

class Foo {
  Future<void> bar() async {}
}

class MockFoo extends Mock implements Foo {}

void main() {
  test('Foo', () {
    final foo = MockFoo();
    when(() => foo.bar()).thenAnswerWithVoid();
    expect(foo.bar(), completes);
  });
}

extension VoidAnswer on When<Future<void>> {
  void thenAnswerWithVoid() => thenAnswer((_) async {});
}

If you're still having trouble can be please provide a reproduction sample? Thanks 👍

shinayser commented 3 years ago

Forget @felangel I was just being stupid. I forgot to stub the repository class 😅😅😅😅😅😅😅😅😅

Lest just go back in time and forget I've opened this issue. Thanks =D