A mock library for Dart inspired by mockito

Overview

🍹 mocktail

build coverage License: MIT

This repository contains mocking libraries for Dart inspired by mockito.


package:mocktail

Pub

A Dart mocking library which simplifies mocking with null safety support and no manual mocks or code generation.


package:mocktail_image_network

Pub

A Dart package which allows you to mock Image.network in your widget tests with confidence using package:mocktail

Comments
  • Mocking AWS Amplify Session in methods

    Mocking AWS Amplify Session in methods

    Originally posted this on SO here.

    I have a UserRepository class and pass it an Amplify Auth Session object upon being instantiated, which it then stores for later use.

    I'm trying to mock this out in my unit tests. After following the guides, I get this error:

    _TypeError (type 'Null' is not a subtype of type 'Future<AuthSession>')

    I'm not sure what I'm doing wrong, it seems as though my mock and test are correct but the UserRepository isn't using the mock.

    Here is my class:

    class UserRepository extends ChangeNotifier {
      AuthCategory auth;
    
      ....
    
      UserRepository({required this.auth}) {
        fetchAuthSession();
      }
    
      ...
    
      void fetchAuthSession() async {
        try {
          final result = await auth.fetchAuthSession( // <--- Error points here
            options: CognitoSessionOptions(getAWSCredentials: true),
          );
    
          sub = (result as CognitoAuthSession).userSub!;
          token = result.userPoolTokens!.idToken;
    
          await fetchUserData();
    
          notifyListeners();
        } on AuthException catch (e) {
          print(e.message);
        }
      }
    
      ...
    }
    

    Here are my test an mock:

    test("Set isAuthenticated to true", () {
      MockAuth auth = MockAuth();
    
      when(auth.fetchAuthSession).thenAnswer((_) async {
        return Future(
          () => MockAuthSession(),
        );
      });
    
      final user = UserRepository(auth: auth);
    
      expect(user.isAuthenticated, false);
    
      user.setAuthenticatedStatus(true);
      expect(user.isAuthenticated, true);
    });
    
    question 
    opened by garrettlove8 16
  • Unit tests with mocktail pass but 'Null' is not a subtype of type 'Future<>' runtime exception is thrown

    Unit tests with mocktail pass but 'Null' is not a subtype of type 'Future<>' runtime exception is thrown

    Hi @felangel!

    Hope all is well :-)

    I posted this originally on SO here, but after a couple of days, no one seems to have a good answer.

    There are similar issues asking about the same error (e.g. here), but their cause was due to improper mocking. In my case, I seem to have the method properly mocked, yet when I debug in Visual Studio Code with All Exceptions enabled, then I get the runtime exception:

    _TypeError (type 'Null' is not a subtype of type 'Future<AuthenticationToken?>')
    

    If I continue the test past the exception (or simply debug the tests with All Exceptions disabled or simply run them without debugging), all my tests pass ok.

    flutter doctor -v
    [βœ“] Flutter (Channel stable, 2.5.3, on macOS 11.6 20G165 darwin-x64, locale en-US)
        β€’ Flutter version 2.5.3 at /Users/davilin/Documents/Projects/flutter
        β€’ Upstream repository https://github.com/flutter/flutter.git
        β€’ Framework revision 18116933e7 (7 days ago), 2021-10-15 10:46:35 -0700
        β€’ Engine revision d3ea636dc5
        β€’ Dart version 2.14.4
    
    [βœ“] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
        β€’ Android SDK at /Users/davilin/Library/Android/sdk
        β€’ Platform android-31, build-tools 31.0.0
        β€’ Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
        β€’ Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7281165)
        β€’ All Android licenses accepted.
    
    [βœ“] Xcode - develop for iOS and macOS
        β€’ Xcode at /Applications/Xcode.app/Contents/Developer
        β€’ Xcode 13.0, Build version 13A233
        β€’ CocoaPods version 1.11.2
    
    [βœ“] Chrome - develop for the web
        β€’ Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [βœ“] Android Studio (version 2020.3)
        β€’ Android Studio at /Applications/Android Studio.app/Contents
        β€’ Flutter plugin can be installed from:
          πŸ”¨ https://plugins.jetbrains.com/plugin/9212-flutter
        β€’ Dart plugin can be installed from:
          πŸ”¨ https://plugins.jetbrains.com/plugin/6351-dart
        β€’ Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7281165)
    
    [βœ“] VS Code (version 1.61.2)
        β€’ VS Code at /Applications/Visual Studio Code.app/Contents
        β€’ Flutter extension version 3.27.0
    
    [βœ“] Connected device (2 available)
        β€’ Davi’s iPhone (mobile) β€’ 3ad3d60608b32fc9683368619da2e4da310ab7f2 β€’ ios            β€’ iOS 12.5.5 16H62
        β€’ Chrome (web)           β€’ chrome                                   β€’ web-javascript β€’ Google Chrome 94.0.4606.81
    
    dependencies:
      hive: ^2.0.4
      hive_flutter: ^1.1.0
    
    dev_dependencies:
      mocktail: ^0.1.4
    
    import 'package:hive/hive.dart';
    
    class AuthenticationRepository {
      static const _currentTokenKey = 'key';
      AuthenticationToken? _inMemoryToken;
      Future<Box<AuthenticationToken?>> _tokenBox;
      ...
      Future<AuthenticationToken?> activeToken() async =>
          _inMemoryToken ?? (await _tokenBox).get(_currentTokenKey);
      ...
    }
    

    Sample test file:

    import 'package:app/src/data/authentication/repository.dart';
    import 'package:flutter_test/flutter_test.dart';
    import 'package:mocktail/mocktail.dart';
    
    class MockAuthenticationRepository extends Mock
        implements AuthenticationRepository {}
    
    void main() {
      AuthenticationRepository authenticationRepository;
      SUT sut; // SUT depends on AuthenticationRepository
    
      setUp(() {
        authenticationRepository = MockAuthenticationRepository();
    
        when(() => authenticationRepository.activeToken())
          .thenAnswer((realInvocation) => Future.value(AuthenticationToken()));
        
        sut = SUT(authenticationRepository);
      });
    
      test('some test', () async {
        await sut.someMethod();
        verify(() => authenticationRepository.activeToken()).called(1);
      });
    }
    

    [mocktail exception]2

    Here is the stack trace:

    MockAuthenticationRepository.activeToken (/Users/davilin/Documents/Projects/app/flutter/app/lib/src/data/authentication/repository.dart:296)
    main.initMocks.<anonymous closure> (/Users/davilin/Documents/Projects/app/flutter/app/test/network/token_refresh_interceptor_test.dart:33)
    when.<anonymous closure> (/Users/davilin/.pub-cache/hosted/pub.dartlang.org/mocktail-0.1.4/lib/src/mocktail.dart:211)
    main.initMocks (/Users/davilin/Documents/Projects/app/flutter/app/test/network/token_refresh_interceptor_test.dart:33)
    main.<anonymous closure>.<anonymous closure> (/Users/davilin/Documents/Projects/app/flutter/app/test/network/token_refresh_interceptor_test.dart:52)
    Declarer._runSetUps.<anonymous closure> (/Users/davilin/.pub-cache/hosted/pub.dartlang.org/test_api-0.4.2/lib/src/backend/declarer.dart:329)
    Future.forEach.<anonymous closure> (dart:async/future.dart:495)
    Future.doWhile.<anonymous closure> (dart:async/future.dart:535)
    StackZoneSpecification._registerUnaryCallback.<anonymous closure>.<anonymous closure> (/Users/davilin/.pub-cache/hosted/pub.dartlang.org/stack_trace-1.10.0/lib/src/stack_zone_specification.dart:126)
    StackZoneSpecification._run (/Users/davilin/.pub-cache/hosted/pub.dartlang.org/stack_trace-1.10.0/lib/src/stack_zone_specification.dart:208)
    StackZoneSpecification._registerUnaryCallback.<anonymous closure> (/Users/davilin/.pub-cache/hosted/pub.dartlang.org/stack_trace-1.10.0/lib/src/stack_zone_specification.dart:126)
    _rootRunUnary (dart:async/zone.dart:1436)
    _CustomZone.runUnary (dart:async/zone.dart:1335)
    _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244)
    _CustomZone.bindUnaryCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1281)
    Future.doWhile (dart:async/future.dart:551)
    Future.forEach (dart:async/future.dart:493)
    Declarer._runSetUps (/Users/davilin/.pub-cache/hosted/pub.dartlang.org/test_api-0.4.2/lib/src/backend/declarer.dart:329)
    <asynchronous gap> (Unknown Source:0)
    StackZoneSpecification._registerUnaryCallback.<anonymous closure> (/Users/davilin/.pub-cache/hosted/pub.dartlang.org/stack_trace-1.10.0/lib/src/stack_zone_specification.dart:0)
    <asynchronous gap> (Unknown Source:0)
    

    Some feedback on SO suggested it may be due to optional variable types I'm passing back from the function, but after trying the following to make what I'm returning explicitly non-optional, the same exception occurs:

    Future<AuthenticationToken?> activeToken() => Future<AuthenticationToken?>(() => const AuthenticationToken()); 
    
    Future<AuthenticationToken?> activeToken() async => const AuthenticationToken();
    
    Future<AuthenticationToken?> activeToken() => _activeToken(); 
    Future<AuthenticationToken?> _activeToken() async => _inMemoryToken ?? (await _tokenBox).get(_currentTokenKey);
    

    Finally, making the return type an optional Future does avoid the exception, but implies something wrong about mocktail, such that it is expecting an optional Future as the return type, whereas the actual return type is explicitly non-optional. And, of course, this wouldn't work as a real solution, because it complicates the calling code.

    Future<AuthenticationToken?>? activeToken() async =>
        _inMemoryToken ?? (await _tokenBox).get(_currentTokenKey);
    

    Thanks for reading and if you can shed some light on this!

    question 
    opened by davejlin 16
  • Adding thenAnswerWithVoid

    Adding thenAnswerWithVoid

    Added a new method to prevent weird and boring usages of the mocks on stubs, like:

    when(() => foo.futureVoidFunction()).thenAnswer((invocation) => Future.value());

    Now you can just:

    when(() => foo.futureVoidFunction()).thenAnswerWithVoid();

    Status

    READY

    Breaking Changes

    NO

    Description

    Adds a convenience method.

    Type of Change

    • [x] ✨ New feature (non-breaking change which adds functionality)
    • [ ] πŸ› οΈ Bug fix (non-breaking change which fixes an issue)
    • [ ] ❌ Breaking change (fix or feature that would cause existing functionality to change)
    • [ ] 🧹 Code refactor
    • [ ] βœ… Build configuration change
    • [ ] πŸ“ Documentation
    • [ ] πŸ—‘οΈ Chore
    opened by shinayser 14
  • Throws type 'Null' is not a subtype of type 'Future<void>'

    Throws type 'Null' is not a subtype of type 'Future'

    I think I found a bug, mostly with the error message throw that can causes confusion:

    Consider the following classes:

    class DataProvider {
      Future<void> justAFutureFunction() async {
        print('Ok, nothing wrong here');
      }
    }
    
    class JustARepository {
      final DataProvider innerRepo;
    
      JustARepository(this.innerRepo);
    
      Future<void> doSomethingWithTheRepository() async {
        await innerRepo.justAFutureFunction();
        print('Everything is ok');
      }
    }
    

    Now the following test that mocks the DataProvider call and everything works fine:

    class MockInnerRepo extends Mock implements DataProvider {}
    
    void main() {
      test('Test', () {
        final innerRepo = MockInnerRepo();
        final outerRepo = JustARepository(innerRepo);
    
        when(() => innerRepo.justAFutureFunction())
            .thenAnswer((invocation) => Future.value());
    
        expect(outerRepo.doSomethingWithTheRepository(), completes);
      });
    }
    

    Now if you add a second when call, that mocks the method from the repository, we get the error: type 'Null' is not a subtype of type 'Future<void>:

    class MockInnerRepo extends Mock implements DataProvider {}
    
    void main() {
      test('Test', () {
        final innerRepo = MockInnerRepo();
        final outerRepo = JustARepository(innerRepo);
    
        when(() => innerRepo.justAFutureFunction())
            .thenAnswer((invocation) => Future.value());
    
        /// This code causes the test to break
        when(() => outerRepo.doSomethingWithTheRepository())
            .thenAnswer((invocation) => Future.value());
    
        expect(outerRepo.doSomethingWithTheRepository(), completes);
      });
    }
    

    I know that calling a method from something that is not being mocked sounds stupid, but this code above actually works with mockito. I spend about 2 hours trying to figure out what I was doing wrong and the error was the way I wrote thet test itself. But like I said, everything was passing with mockito.

    Maybe telling the user that we should mock the Repository before trying to call when on it?

    question 
    opened by shinayser 14
  • Not sure how to verify a void method was called

    Not sure how to verify a void method was called

    Describe the bug Given 2 classes A and B, when A uses a void method of B, we can't verify that this call happens.

    To Reproduce Full example in one simple file: https://gist.github.com/svarlet/337c0d3234cc3ba67c7d96adf788c092 Run the test, the output shows an error:

    NoSuchMethodError: Class 'DemoDouble' has no instance method 'doSomething' with matching arguments.
    Receiver: Instance of 'DemoDouble'
    Tried calling: doSomething(1)
    Found: doSomething(int) => void
    

    Expected behavior I appreciate that the method is not stubbed, thus Mocktail is correctly reporting it to me. However, the following doesn't solve the problem:

    when(_demo).calls(#doSomething);
    

    but this one does:

    when(_demo).calls(#doSomething).thenReturn(1);
    

    Yet, this is a void function, so it feels wrong. Is there another way? What am I missing?

    question 
    opened by svarlet 12
  • Cubit Testing: Bad state: A test tried to use `any` or `captureAny` on a parameter of type `T State`, but registerFallbackValue was not previously called to register a fallback value for `T State`

    Cubit Testing: Bad state: A test tried to use `any` or `captureAny` on a parameter of type `T State`, but registerFallbackValue was not previously called to register a fallback value for `T State`

    Describe the bug I'm migrating one personal project to the latest versions and null safety. But I'm having problems doing widget testing on the latest version with mocktail and cubit.

    **Test I'm trying to run **

    import 'package:bloc_test/bloc_test.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_bloc/flutter_bloc.dart';
    import 'package:flutter_test/flutter_test.dart';
    import 'package:mocktail/mocktail.dart';
    
    import 'package:qr_generator/qr_generator.dart';
    import 'package:qr_generator_flutter/src/features/qr_generator/logic/qr_generator_cubit.dart';
    import 'package:qr_generator_flutter/src/features/qr_generator/logic/qr_generator_state.dart';
    import 'package:qr_generator_flutter/src/features/qr_generator/views/qr_generator_page.dart';
    import 'package:qr_generator_flutter/src/features/qr_generator/views/qr_generator_page_i18n.dart';
    import 'package:qr_generator_flutter/src/features/qr_scanner/logic/qr_scanner_cubit.dart';
    import 'package:qr_generator_flutter/src/features/qr_scanner/logic/qr_scanner_state.dart'
        as scanner_s;
    import 'package:qr_generator_flutter/src/features/qr_scanner/views/qr_scanner_page.dart';
    import 'package:qr_generator_flutter/src/features/qr_generator/views/widgets/qr_code_widget.dart';
    
    class MockGetSeed extends Mock implements GetSeed {}
    
    class MockQrGeneratorCubit extends MockCubit<QrGeneratorState>
        implements QrGeneratorCubit {}
    
    class MockQrScannerCubit extends MockCubit<scanner_s.QrScannerState>
        implements QrScannerCubit {}
    
    void main() {
      group('QrGeneratorPage', () {
        final tSeed = Seed(
          seed: 'seed',
          expiresAt: DateTime.now().add(const Duration(seconds: 15)),
        );
    
        late QrGeneratorCubit qrGeneratorCubit;
        late QrScannerCubit qrScannerCubit;
    
        setUp(() {
          qrGeneratorCubit = MockQrGeneratorCubit();
          qrScannerCubit = MockQrScannerCubit();
        });
    
        testWidgets('renders a QrGeneratorPage', (tester) async {
          ///arrange
          when(() => qrGeneratorCubit.state)
              .thenReturn(const QrGeneratorState.initial());
    
          ///act
          await tester.pumpWidget(BlocProvider.value(
            value: qrGeneratorCubit,
            child: const MaterialApp(home: QrGeneratorPage()),
          ));
    
          ///expect
          expect(find.byKey(const Key('kBodyKey')), findsOneWidget);
        });
      });
    }
    
    

    Error I'm getting

    //Bad state: A test tried to use `any` or `captureAny` on a parameter of type `QrGeneratorState`, but
    //registerFallbackValue was not previously called to register a fallback value for `QrGeneratorState`
    
    To fix, do:
    
    
    void main() {
      setUpAll(() {
        registerFallbackValue<QrGeneratorState>(QrGeneratorState());
      });
    }
    
    
    //If you cannot easily create an instance of QrGeneratorState, consider defining a `Fake`:
    
    
    class QrGeneratorStateFake extends Fake implements QrGeneratorState {}
    
    void main() {
      setUpAll(() {
        registerFallbackValue<QrGeneratorState>(QrGeneratorStateFake());
      });
    }
    

    I already tried doing what the error message says, but I'm still getting the same error.

    question 
    opened by elianortega 10
  • `When` throws exception when stubbing response

    `When` throws exception when stubbing response

    Here we have:

    class Cat {
      Future<void> hunt(String place, String prey) async => prey;
    }
    

    then in test file: [for demonstration, test doesn't do anything]

    class MockCat extends Mock implements Cat {}
    
    void main() {
    late MockCat cat;
    setUp(() {
        cat = MockCat();
      });
    
    group('Cat behaviors', () {
        test('verify cat can hunt', () {
          when(() => cat.hunt('yard', 'mouse')).thenAnswer((invocation) async => 'mouse');
        });
      });
    }
    

    then it throws

    _TypeError (type 'Null' is not a subtype of type 'Future<void>')
    

    I have upgraded 'bloc_test' to 8.0.0 and while updating the tests because of syntax change, I face the above error.

    What am I doing wrong?

    Flutter doctor
    [βœ“] Flutter (Channel beta, 2.0.1, on macOS 11.0.1 20B29 darwin-x64, locale en-US)
        β€’ Flutter version 2.0.1 at /Users/hashem/Desktop/Xcode_Projects/flutter
        β€’ Framework revision c5a4b4029c (2 weeks ago), 2021-03-04 09:47:48 -0800
        β€’ Engine revision 40441def69
        β€’ Dart version 2.12.0
    
    [βœ“] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
        β€’ Android SDK at /Users/hashem/Library/Android/sdk
        β€’ Platform android-30, build-tools 30.0.2
        β€’ Java binary at: /Applications/Android
          Studio.app/Contents/jre/jdk/Contents/Home/bin/java
        β€’ Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
        β€’ All Android licenses accepted.
    
    [βœ“] Xcode - develop for iOS and macOS
        β€’ Xcode at /Applications/Xcode.app/Contents/Developer
        β€’ Xcode 12.4, Build version 12D4e
        β€’ CocoaPods version 1.10.1
    
    [βœ“] Chrome - develop for the web
        β€’ Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [βœ“] Android Studio (version 4.1)
        β€’ Android Studio at /Applications/Android Studio.app/Contents
        β€’ Flutter plugin can be installed from:
          πŸ”¨ https://plugins.jetbrains.com/plugin/9212-flutter
        β€’ Dart plugin can be installed from:
          πŸ”¨ https://plugins.jetbrains.com/plugin/6351-dart
        β€’ Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
    
    [βœ“] VS Code (version 1.54.3)
        β€’ VS Code at /Applications/Visual Studio Code.app/Contents
        β€’ Flutter extension version 3.20.0
    
    [βœ“] Connected device (3 available)
        β€’ Hashem’s iPhone (mobile)   β€’ 00008030-00124C3021BA802E            β€’ ios            β€’
          iOS 14.4
        β€’ iPhone 12 Pro Max (mobile) β€’ 6E489C41-27D7-4EE7-A1A7-3383C53F1452 β€’ ios            β€’
          com.apple.CoreSimulator.SimRuntime.iOS-14-4 (simulator)
        β€’ Chrome (web)               β€’ chrome                               β€’ web-javascript β€’
          Google Chrome 89.0.4389.90
    
    β€’ No issues found!
    
    question 
    opened by haashem 9
  • Cannot install package `mocktail v0.3.0` with `build_runner 2.3.2` - version solving fails

    Cannot install package `mocktail v0.3.0` with `build_runner 2.3.2` - version solving fails

    Describe the bug

    it's not possible to use mocktail with build_runner - both current versions - seem to clash and version solving reports an error.

    The current mocktail package v0.3.0 is not building when added to a new project.

    When you run flutter pub get with mocktail having been just added, you get the following error:

    --
    
    [mocktail_test] flutter pub get
    Running "flutter pub get" in mocktail_test...                    1,216ms
    exit code 0
    
    --
    
    [mocktail_test] flutter pub get
    Running "flutter pub get" in mocktail_test...                   
    Because no versions of test match >1.21.4 <1.21.5 and test >=1.16.0-nullsafety.19 <1.16.6 depends on test_api 0.2.19, test >=1.16.0-nullsafety.19 <1.16.6-∞ or >1.21.4 <1.21.5-∞ requires test_api 0.2.19.
    And because test >=1.16.6 <1.17.10 depends on analyzer ^1.0.0, test >=1.16.0-nullsafety.19 <1.17.10-∞ or >1.21.4 <1.21.5-∞ requires test_api 0.2.19 or analyzer ^1.0.0.
    And because test >=1.17.10 <1.20.0 depends on analyzer >=1.0.0 <3.0.0 and test >=1.20.0 <1.21.2 depends on test_api 0.4.9, test >=1.16.0-nullsafety.19 <1.21.2-∞ or >1.21.4 <1.21.5-∞ requires test_api 0.2.19 or 0.4.9 or analyzer >=1.0.0 <3.0.0.
    And because test >=1.21.2 <1.21.3 depends on test_api 0.4.10 and test >=1.21.3 <1.21.4 depends on test_api 0.4.11, test >=1.16.0-nullsafety.19 <1.21.4-∞ or >1.21.4 <1.21.5-∞ requires test_api 0.2.19 or 0.4.9 or 0.4.10 or 0.4.11 or analyzer >=1.0.0 <3.0.0.
    And because test >=1.21.5 <1.21.6 depends on test_api 0.4.13 and test >=1.21.6 <1.21.7 depends on test_api 0.4.14, test >=1.16.0-nullsafety.19 <1.21.4-∞ or >1.21.4 <1.21.7-∞ requires test_api 0.2.19 or 0.4.9 or 0.4.10 or 0.4.11 or 0.4.13 or 0.4.14 or analyzer >=1.0.0 <3.0.0.
    And because test >=1.21.7 <1.22.0 depends on test_api 0.4.15 and test >=1.22.0 depends on test_api 0.4.16, test >=1.16.0-nullsafety.19 <1.21.4-∞ or >1.21.4 requires test_api 0.2.19 or 0.4.9 or 0.4.10 or 0.4.11 or 0.4.13 or 0.4.14 or 0.4.15 or 0.4.16 or analyzer >=1.0.0 <3.0.0.
    And because test 1.21.4 depends on test_core 0.4.16 which depends on frontend_server_client ^2.1.0, test >=1.16.0-nullsafety.19 requires test_api 0.2.19 or 0.4.9 or 0.4.10 or 0.4.11 or 0.4.13 or 0.4.14 or 0.4.15 or 0.4.16 or analyzer >=1.0.0 <3.0.0 or frontend_server_client ^2.1.0.
    And because build_runner >=2.2.1 depends on analyzer >=4.4.0 <6.0.0 and every version of flutter_test from sdk depends on test_api 0.4.12, if flutter_test from sdk and test >=1.16.0-nullsafety.19 and build_runner >=2.2.1 then frontend_server_client ^2.1.0.
    And because build_runner >=2.3.1 depends on frontend_server_client ^3.0.0 and mocktail 0.3.0 depends on test ^1.16.0, one of flutter_test from sdk or build_runner >=2.3.1 or mocktail 0.3.0 must be false.
    And because no versions of mocktail match >0.3.0 <0.4.0 and mocktail_test depends on mocktail ^0.3.0, flutter_test from sdk is incompatible with build_runner >=2.3.1.
    So, because mocktail_test depends on both build_runner ^2.3.2 and flutter_test from sdk, version solving failed.
    pub get failed (1; So, because mocktail_test depends on both build_runner ^2.3.2 and flutter_test from sdk, version solving failed.)
    exit code 1
    
    

    To Reproduce Steps to reproduce the behavior:

    1. In VSCode, start a new flutter project
    2. Add mocktail to your pubspect.yaml's dev dependencies
    3. Add 'build_runner to your pubspect.yaml's dev dependencies`
    4. Run flutter pub get

    When you run flutter pub get you will see the version solving error .

    Expected behavior I expected flutter pub get to not fail.

    Logs Run flutter analyze and attach any output of that command below.

    dtal@thing4: flutter analyze
    Analyzing lib...                                                
    No issues found! (ran in 1.7s)
    

    Paste the output of running flutter doctor -v here.

    dtal@thing4: flutter doctor -v
    [βœ“] Flutter (Channel stable, 3.3.7, on Debian GNU/Linux 11 (bullseye)
        5.10.0-18-amd64, locale en_US.UTF-8)
        β€’ Flutter version 3.3.7 on channel stable at /home/dtal/local/flutter
        β€’ Upstream repository https://github.com/flutter/flutter.git
        β€’ Framework revision e99c9c7cd9 (8 days ago), 2022-11-01 16:59:00 -0700
        β€’ Engine revision 857bd6b74c
        β€’ Dart version 2.18.4
        β€’ DevTools version 2.15.0
    
    [βœ“] Android toolchain - develop for Android devices (Android SDK version
        32.1.0-rc1)
        β€’ Android SDK at /home/dtal/Android/Sdk
        β€’ Platform android-32, build-tools 32.1.0-rc1
        β€’ Java binary at: /usr/local/src/android-studio/jre/bin/java
        β€’ Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
        β€’ All Android licenses accepted.
    
    [βœ“] Chrome - develop for the web
        β€’ CHROME_EXECUTABLE = chromium
    
    [βœ“] Linux toolchain - develop for Linux desktop
        β€’ Debian clang version 11.0.1-2
        β€’ cmake version 3.18.4
        β€’ ninja version 1.10.1
        β€’ pkg-config version 0.29.2
    
    [βœ“] Android Studio (version 2021.1)
        β€’ Android Studio at /usr/local/src/android-studio
        β€’ Flutter plugin version 66.0.1
        β€’ Dart plugin version 211.7817
        β€’ Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
    
    [βœ“] VS Code (version 1.73.0)
        β€’ VS Code at /usr/share/code
        β€’ Flutter extension version 3.52.0
    
    [βœ“] Connected device (3 available)
        β€’ Android SDK built for x86 (mobile) β€’ emulator-5554 β€’ android-x86    β€’
          Android 8.0.0 (API 26) (emulator)
        β€’ Linux (desktop)                    β€’ linux         β€’ linux-x64      β€’
          Debian GNU/Linux 11 (bullseye) 5.10.0-18-amd64
        β€’ Chrome (web)                       β€’ chrome        β€’ web-javascript β€’
          Chromium 107.0.5304.87 built on Debian 11.5, running on Debian 11.5
    
    [βœ“] HTTP Host Availability
        β€’ All required HTTP hosts are available
    
    β€’ No issues found!
    
    question 
    opened by dorontal 8
  • dart 2.19 doesn't delegate inaccessible private names to noSuchMethod.

    dart 2.19 doesn't delegate inaccessible private names to noSuchMethod.

    Is your feature request related to a problem? Please describe.

    Dart 2.19 doesn't delegate inaccessible private names to noSuchMethod.

    https://github.com/dart-lang/sdk/blob/main/CHANGELOG.md#2190 https://github.com/dart-lang/language/issues/2020 https://github.com/dart-lang/sdk/issues/49687 https://github.com/dart-lang/site-www/issues/4263

    https://github.com/mobxjs/mobx.dart/blob/master/mobx/test/observable_test.dart The test fails on dart 2.19.

    https://github.com/mobxjs/mobx.dart/actions/runs/3262020308/jobs/5359681093

    Describe the solution you'd like A clear and concise description of what you want to happen.

    Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

    Additional context Add any other context or screenshots about the feature request here.

    question 
    opened by amondnet 8
  • when Throws Exceptions Under the Hood

    when Throws Exceptions Under the Hood

    Describe the bug when causes exceptions to be thrown in the class you are mocking under the hood. You probably won't notice them if you're not debugging with the option to catch all exceptions in the debugger, but this is what happens when you turn that option on:

    TestClass

    class TestClass {
      Future<String> get hello async {
        return "Hello World";
      }
    }
    

    Test code:

    import 'package:mocktail/mocktail.dart';
    import 'package:mocktail_exceptions/shared.dart';
    import 'package:test/test.dart';
    
    class MockTestClass extends Mock implements TestClass {}
    
    void main() {
      test('test', () async {
        var mockTestClass = MockTestClass();
        when(() => mockTestClass.hello).thenAnswer((_) async => 'Hi');
        print(await mockTestClass.hello);
      });
    }
    

    Result: image

    To Reproduce

    • Clone this repoor grab the code in the Flutter/mocktail_exceptions folder
    • Open with vscode (You might be able to reproduce with Android studio, but I can't explain the steps)
    • Ensure you have these debugging options turned on image
    • Debug the mocktail_test.dart test
    • You will see the exception. The debugger will hit the line in TestClass above
    • Note that this does not happen with Mockito. You can try the same thing with the mockito_test.dart. It does not throw an exception

    Note: This does not stop the test from passing. If you run either test without the debugger, it will pass.

    Expected behavior The test should not throw exceptions. The problem is that we should be able to run Dart code with the debugger turned on and never see exceptions unless something exceptional happens. The fact that the mocks throw exceptions means that we see false negatives when trying to debug.

    Screenshots image

    Logs

    Analyzing mocktail_exceptions...
    No issues found! (ran in 1.4s)

    [βœ“] Flutter (Channel stable, 3.3.9, on macOS 13.0 22A380 darwin-x64, locale en-AU) β€’ Flutter version 3.3.9 on channel stable at /usr/local/Caskroom/flutter/3.0.2/flutter β€’ Upstream repository https://github.com/flutter/flutter.git β€’ Framework revision b8f7f1f986 (3 weeks ago), 2022-11-23 06:43:51 +0900 β€’ Engine revision 8f2221fbef β€’ Dart version 2.18.5 β€’ DevTools version 2.15.0

    [βœ“] Android toolchain - develop for Android devices (Android SDK version 33.0.0) β€’ Android SDK at /Users/christianfindlay/Library/Android/sdk β€’ Platform android-33, build-tools 33.0.0 β€’ Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java β€’ Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866) β€’ All Android licenses accepted.

    [βœ“] Xcode - develop for iOS and macOS (Xcode 14.1) β€’ Xcode at /Applications/Xcode.app/Contents/Developer β€’ Build 14B47b β€’ CocoaPods version 1.11.3

    [βœ“] Chrome - develop for the web β€’ Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

    [βœ“] Android Studio (version 2021.3) β€’ Android Studio at /Applications/Android Studio.app/Contents β€’ Flutter plugin can be installed from: πŸ”¨ https://plugins.jetbrains.com/plugin/9212-flutter β€’ Dart plugin can be installed from: πŸ”¨ https://plugins.jetbrains.com/plugin/6351-dart β€’ Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

    [βœ“] VS Code (version 1.68.1) β€’ VS Code at /Users/christianfindlay/Downloads/Visual Studio Code.app/Contents β€’ Flutter extension version 3.54.0

    [βœ“] Connected device (3 available) β€’ sdk gphone64 x86 64 (mobile) β€’ emulator-5554 β€’ android-x64 β€’ Android 13 (API 33) (emulator) β€’ macOS (desktop) β€’ macos β€’ darwin-x64 β€’ macOS 13.0 22A380 darwin-x64 β€’ Chrome (web) β€’ chrome β€’ web-javascript β€’ Google Chrome 108.0.5359.124

    [βœ“] HTTP Host Availability β€’ All required HTTP hosts are available

    Additional context I looked through the stack trace and don't have a complete answer for why this is happening, but I suspect that mocktail is somehow partially invoking the method call. It's weird that it even cares about the class that it implements, given that the mock class does not even extend it.

    question waiting for response 
    opened by MelbourneDeveloper 7
  • Add missing fallback value

    Add missing fallback value

    Status

    READY

    Breaking Changes

    NO

    Description

    A fallback value for Map<String, Object?> was missing, probably because of an oversight as a fallback for Map<String, Object> was registered twice. I also added an assertion to check that _createInitialFallbackValues doesn't create a fallback twice for the same type.

    Type of Change

    • [ ] ✨ New feature (non-breaking change which adds functionality)
    • [x] πŸ› οΈ Bug fix (non-breaking change which fixes an issue)
    • [ ] ❌ Breaking change (fix or feature that would cause existing functionality to change)
    • [ ] 🧹 Code refactor
    • [ ] βœ… Build configuration change
    • [ ] πŸ“ Documentation
    • [ ] πŸ—‘οΈ Chore
    enhancement 
    opened by miDeb 7
  • Can't use any() to verify StackTrace

    Can't use any() to verify StackTrace

    Bug Description In this method, I want to catch the exception and the stack trace. I got into trouble when I want to verify the broadcastPort.notifyCoreEvent(). This is the method I want to test:

    real_method.dart:

    @override
    Future<CategoryDto> addCategory(CategoryDto category) async {
      try {
        Category(category).validate(insert: true);
        final result = await persistencePort.createCategory(category);
    
        broadcastPort?.notifyCoreEvent(
          CoreEvent.categoryCreatedEvent,
          request: category,
          response: result,
        );
    
        return result;
      } catch (e, s) {
        broadcastPort?.notifyCoreEvent(
          CoreEvent.exceptionThrownEvent,
          exception: e,
          stackTrace: s,
        );
    
        rethrow;
      }
    }
    

    This is how I tested it:

    real_method_test.dart:

    class FakeCoreDomainException extends Fake implements CoreDomainException {}
    class FakeStackTrace extends Fake implements StackTrace {}
    
    // Test's main starts here...
    
    setUpAll(() {
      registerFallbackValue(CoreEvent.exceptionThrownEvent);
      registerFallbackValue(FakeCoreDomainException());
      registerFallbackValue(FakeStackTrace());
    });
    
    // Some statements here...
    
    test('Insert invalid category and broadcast port is not omitted, insertion failed', () async {
      final exception =
          CoreDomainException(CoreDomainExceptionType.invalidCategoryTitle);
    
      when(() => mockPersistencePort.createCategory(dummyCategoryDto))
          .thenThrow(exception);
    
      expect(
        () => coreService.addCategory(dummyCategoryDto),
        throwsA(
          exception,
        ),
      );
    
      verify(() => mockPersistencePort.createCategory(dummyCategoryDto))
          .called(1);
    
      verify(
        () => mockBroadcastPort.notifyCoreEvent(
          CoreEvent.exceptionThrownEvent,
          exception: exception,
          stackTrace: any(),
        ),
      ).called(1);
    });
    

    But I got this error:

    Invalid argument(s): An argument matcher (like `any()`) was either not used as an immediate argument to Symbol("notifyCoreEvent") (argument matchers can only be used as an argument for the very method being stubbed or verified), or was used as a named argument without the Mocktail "named" API (Each argument matcher that is used as a named argument needs to specify the name of the argument it is being used in. For example: `when(() => obj.fn(x: any(named: "x")))`).

    I tried to change stackTrace: any() tostackTrace: any(that: isA<StackTrace>()), but still got this error.

    By the way, If I omit the stack trace on the real method call, the test will be passed.

    modified_real_method.dart:

    @override
    Future<CategoryDto> addCategory(CategoryDto category) async {
      try {
    
      // Some statements here...
    
      } catch (e) {
        broadcastPort?.notifyCoreEvent(
          CoreEvent.exceptionThrownEvent,
          exception: e,
        );
    
        rethrow;
      }
    }
    

    modified_real_method_test.dart:

    setUpAll(() {
      registerFallbackValue(CoreEvent.exceptionThrownEvent);
    });
    
    // Some statements here...
    
    test('Insert invalid category and broadcast port is not omitted, insertion failed', () async {
      final exception =
          CoreDomainException(CoreDomainExceptionType.invalidCategoryTitle);
    
      when(() => mockPersistencePort.createCategory(dummyCategoryDto))
          .thenThrow(exception);
    
      expect(
        () => coreService.addCategory(dummyCategoryDto),
        throwsA(
          exception,
        ),
      );
    
      verify(() => mockPersistencePort.createCategory(dummyCategoryDto))
          .called(1);
    
      verify(
        () => mockBroadcastPort.notifyCoreEvent(
          CoreEvent.exceptionThrownEvent,
          exception: exception,
        ),
      ).called(1);
    });
    

    Expected behavior stackTrace: any() should be enough to make real_method_test.dart passed. Because I have another similar use case for verifying mockNavigatorObserver.didPush() and it is working.

    class FakeRoute extends Fake implements Route {}
    
    // Test's main starts here...
    
    testWidget('Some navigation test', () {
      setUpAll(() {
        registerFallbackValue(FakeRoute());
      }
    
      // Some statements here...
    
      await tester.pumpWidget(
        MultiRepositoryProvider(
          providers: [
            RepositoryProvider<BaseLocationService>.value(
              value: mockLocationService,
            ),
          ],
          child: MultiBlocProvider(
            providers: [
              BlocProvider<LocationCubit>(
                create: (_) => mockLocationCubit,
              ),
            ],
            child: MaterialApp(
              onGenerateRoute: _appRouter.onGenerateRoute,
              navigatorObservers: [mockNavigatorObserver],
              home: const ActivateLocationScreen(),
            ),
          ),
        ),
      );
    
      // Some statements here...
    
      verify(() => mockNavigatorObserver.didPush(any(), any()));
    });
    

    Environment Dart: 2.18.4 (My project is a dart package) Mocktail: 0.3.0

    Additional context I am thinking that maybe we can provide an optional StackTrace parameter on the thenThrow()

    opened by tijanirf 0
  • Verifying nested closures does not work properly

    Verifying nested closures does not work properly

    Can't mock method for calling closure from parameter I'm trying to mock a method that has in parameter callback and it should be called in when().thanAnswer().

    To Reproduce run this code

    import 'package:flutter_test/flutter_test.dart';
    import 'package:mocktail/mocktail.dart';
    
    class MockDependency extends Mock implements Dependency {}
    
    class MockExecutor extends Mock implements Executor {}
    
    void main() {
      final dependency = MockDependency();
      final executor = MockExecutor();
      final subject = Subject(executor, dependency);
    
      group('Closures', () {
        final Map mockedData = {'mockedData': 2};
        test('try nester closure verify', () {
          when(() => dependency.getData()).thenAnswer((_) async => mockedData);
          when(() => executor.execute(any(that: const TypeMatcher<Function>())))
              .thenAnswer((invocation) async =>
                  await invocation.positionalArguments.first.call());
    
          final res = subject.test();
    
          verify(() => dependency.getData()).called(1);
          expect(res, mockedData);
        });
      });
    }
    
    class Dependency {
      Future<Map> getData() async {
        return {'data': 1};
      }
    }
    
    class Subject {
      final Executor executor;
      final Dependency dependency;
    
      Subject(this.executor, this.dependency);
    
      Future<Map> test() async {
        return executor.execute(() async => await dependency.getData());
      }
    }
    
    class Executor {
      T execute<T>(T Function() callback) {
        return callback();
      }
    }
    

    Expected behavior Should verify method call and expect mocked value.

    Logs

    Connecting to VM Service at http://127.0.0.1:51656/kGetGlBOB8U=/ws
    No matching calls (actually, no calls at all).
    (If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
    package:test_api                           fail
    _VerifyCall._checkWith
    package:mocktail/src/mocktail.dart:722
    _makeVerify.<fn>
    package:mocktail/src/mocktail.dart:515
    main.<fn>.<fn>
    test/…/repository/test_test.dart:23
    2
    
    type 'Null' is not a subtype of type 'FutureOr<Map<dynamic, dynamic>>'
    MockExecutor.execute
    test/…/repository/test_test.dart:47
    Subject.test
    test/…/repository/test_test.dart:42
    main.<fn>.<fn>
    test/…/repository/test_test.dart:21
    ===== asynchronous gap ===========================
    dart:async                                 _completeOnAsyncError
    main.<fn>.<fn>
    test/…/repository/test_test.dart:21
    2
    
    βœ– Closures try nester closure verify
    Exited (1)
    
    [βœ“] Flutter (Channel stable, 3.3.3, on macOS 12.6 21G115 darwin-arm, locale en-GB)
        β€’ Flutter version 3.3.3 on channel stable at /Users/ivan/fvm/versions/3.3.3
        β€’ Upstream repository https://github.com/flutter/flutter.git
        β€’ Framework revision 18a827f393 (2 months ago), 2022-09-28 10:03:14 -0700
        β€’ Engine revision 5c984c26eb
        β€’ Dart version 2.18.2
        β€’ DevTools version 2.15.0
    
    [βœ“] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
        β€’ Android SDK at /Users/ivan/Library/Android/sdk
        β€’ Platform android-33, build-tools 32.0.0
        β€’ ANDROID_HOME = /Users/ivan/Library/Android/sdk
        β€’ Java binary at: /Users/ivan/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/213.7172.25.2113.9014738/Android Studio.app/Contents/jre/Contents/Home/bin/java
        β€’ Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
        β€’ All Android licenses accepted.
    
    [βœ“] Xcode - develop for iOS and macOS (Xcode 14.1)
        β€’ Xcode at /Applications/Xcode.app/Contents/Developer
        β€’ Build 14B47b
        β€’ CocoaPods version 1.11.3
    
    [βœ“] Chrome - develop for the web
        β€’ Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [βœ“] Android Studio (version 2021.3)
        β€’ Android Studio at /Users/ivan/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/213.7172.25.2113.9014738/Android Studio.app/Contents
        β€’ Flutter plugin can be installed from:
          πŸ”¨ https://plugins.jetbrains.com/plugin/9212-flutter
        β€’ Dart plugin can be installed from:
          πŸ”¨ https://plugins.jetbrains.com/plugin/6351-dart
        β€’ Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    
    [βœ“] IntelliJ IDEA Community Edition (version 2022.2.3)
        β€’ IntelliJ at /Users/ivan/Library/Application Support/JetBrains/Toolbox/apps/IDEA-C/ch-0/222.4345.14/IntelliJ IDEA CE.app
        β€’ Flutter plugin can be installed from:
          πŸ”¨ https://plugins.jetbrains.com/plugin/9212-flutter
        β€’ Dart plugin can be installed from:
          πŸ”¨ https://plugins.jetbrains.com/plugin/6351-dart
    
    [βœ“] VS Code (version 1.74.0)
        β€’ VS Code at /Applications/Visual Studio Code.app/Contents
        β€’ Flutter extension version 3.54.0
    
    [βœ“] Connected device (2 available)
        β€’ macOS (desktop) β€’ macos  β€’ darwin-arm64   β€’ macOS 12.6 21G115 darwin-arm
        β€’ Chrome (web)    β€’ chrome β€’ web-javascript β€’ Google Chrome 108.0.5359.98
    
    [βœ“] HTTP Host Availability
        β€’ All required HTTP hosts are available
    
    investigating 
    opened by InAnadea 3
  • Flutter Secure Storage Mock Throws type 'Null' is not a subtype of type 'Future<String?>'

    Flutter Secure Storage Mock Throws type 'Null' is not a subtype of type 'Future'

    Hello, could someone suggest me an idea how to solve this? When im trying to mock flutter secure storage i get this error " type 'Null' is not a subtype of type 'Future<String?> "

    -This is my storage

    import 'package:flutter_secure_storage/flutter_secure_storage.dart';

    abstract class IStorage { Future saveData(String value, String key);

    Future getId(String key); }

    class MyStorage implements IStorage { MyStorage(this._storage); final FlutterSecureStorage _storage; @override Future getId(String key) async { return await _storage.read(key: key) ?? 'No data founded'; }

    @override Future saveData(String value, String key) async { await _storage.write(key: key, value: value); } }

    -My Service

    import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:fixed/shared/storage.dart'; import 'package:flutter/cupertino.dart';

    class ApiService { final String _baseURL = 'https://jsonplaceholder.typicode.com/'; Dio _dio = Dio(BaseOptions()); final IStorage _storage;

    ApiService(this._storage, {Dio? dio}) { _dio = dio ?? Dio(); _dio.options.baseUrl = _baseURL; }

    Future get() async { String id = await _storage.getId('id'); final response = await _dio.get('${_baseURL}posts/$id'); debugPrint(json.encode(response.data)); return json.encode(response.data); } }

    My Test File

    import 'package:dio/dio.dart'; import 'package:fixed/api/api_service.dart'; import 'package:fixed/shared/storage.dart'; import 'package:fixed/store/store1.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http_mock_adapter/http_mock_adapter.dart'; import 'package:mocktail/mocktail.dart';

    class MockStorage extends Mock implements IStorage {}

    class MockStorage2 extends Mock implements MyStorage {}

    class MockFlutterSecureStorage extends Mock implements FlutterSecureStorage {}

    void main() { final dio = Dio(); final dioAdapter = DioAdapter(dio: dio, matcher: const UrlRequestMatcher()); late ApiService service; late MockFlutterSecureStorage mockSecureStorage;

    setUp(() { mockStorage = MockStorage(); mockSecureStorage = MockFlutterSecureStorage(); dio.httpClientAdapter = dioAdapter; service = ApiService(dio: dio, MyStorage(mockSecureStorage)); });

    void mockData() { dioAdapter.onGet('https://jsonplaceholder.typicode.com/posts/1', (request) { return request.reply(200, {'data': 'sucessfull'}); }); }

    void mockGetId() { when(() => mockStorage.getId('id')) .thenAnswer((invocation) => Future.value('1')); }

    group('Test Service', () { test('Test endpoint', () async { //IT THROW ERROR when(() => mockSecureStorage.read(key: 'Γ­d')).thenAnswer((_) async => ''); final data = await service.get(); expect(data, equals('{"data":"sucessfull"}')); verify(() => mockSecureStorage.read(key: 'id')).called(1); });

    }); }

    opened by DiegoVega19 0
  • Invalid argument(s): The

    Invalid argument(s): The "any" argument matcher is used outside of method stubbing (via when) or verification (via verify or untilCalled). This is invalid, and results in bad behavior during the next stubbing or verification.

    class FakeRequest extends Fake implements RequestOptions{}
    
    setUp((){
    registerCallback(FakeRequest())
    });
    
    test("should fetch customer info", () async {
        // arrange
        when(() => mockDioClient.get(any())).thenAnswer(
          (_) async => Response(
            data: fixture("customer_fixture.json"),
            requestOptions: any(),
            statusCode: 200,
          ),
        );
    
        // act
        var result = await profileRemoteDataSourceImpl.getCustomerInfo();
    
        // assert
        expect(result, testCustomerModel);
        verify(() => mockDioClient.get(Urls.getCustomerInfo));
        verifyNoMoreInteractions(mockDioClient);
      });
    
    opened by raxahai 0
  • Arguments with type generics are not properly verified using any()

    Arguments with type generics are not properly verified using any()

    Describe the bug I have the following code:

    class Service {
      Future<void> method<T>(Argument<T> argument) async {
        return;
      }
    }
    
    class Argument<T> extends Equatable {
      Argument(this.value);
    
      final T value;
    
      @override
      List<Object?> get props => [value];
    }
    
    class MockService extends Mock implements Service {}
    

    and then the following test:

    test('should verify the call to method', () async {
      registerFallbackValue(Argument(''));
      final service = MockService();
      when(() => service.method(Argument('value'))).thenAnswer((_) async {});
    
      await service.method(Argument('value'));
      verify(() => service.method(any())).called(1);
    });
    

    This test throws an error

    No matching calls. All calls: MockService.method<String>(Argument<String>(value))
    (If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
    

    If I change the test to instead verify like that:

      verify(() => service.method(Argument('value'))).called(1);
    

    It starts matching the call correctly.

    I would imagine matcher any() should match the same way as Argument('value').

    Also, the issue goes away if I remove the type generic parameter from the service's method declaration.

    If I try to change the mocking to

    when(() => service.method(any())).thenAnswer((_) async {});
    

    Then I get this error

    type 'Null' is not a subtype of type 'Future<void>'
    

    To Reproduce Run the tests with the provided code.

    Expected behavior verify(() => service.method(any())).called(1); should correctly match the call to the mocked service method.

    Additional context Running on flutter stable 3.3.6, with the latest mocktail version 0.3.0

    opened by lukaszdebowski 0
  • style: add very_good_analysis

    style: add very_good_analysis

    Status

    READY

    Breaking Changes

    NO

    Description

    Add very_good_analysis in mocktail and mocktail_image_network

    Type of Change

    • [ ] ✨ New feature (non-breaking change which adds functionality)
    • [ ] πŸ› οΈ Bug fix (non-breaking change which fixes an issue)
    • [x] ❌ Breaking change (fix or feature that would cause existing functionality to change)
    • [x] 🧹 Code refactor
    • [ ] βœ… Build configuration change
    • [ ] πŸ“ Documentation
    • [x] πŸ—‘οΈ Chore
    opened by lsaudon 4
Releases(mocktail-image-network-v0.3.1)
Owner
Felix Angelov
software engineer by day, software engineer by night.
Felix Angelov
An example of how to mock state for testing widgets when using riverpod StateNotifierProvider

Testing Riverpod StateNotifierProvider An example of how to mock state for testing widgets when using riverpod StateNotifierProvider. These tests work

Matthew Rideout 15 Dec 13, 2022
A sample flutter app with mock API for movie details

movie_app A new Flutter project. screenshots Getting Started This project is a starting point for a Flutter application. A few resources to get you st

null 2 Oct 25, 2022
Ethers: A dart library that connects to interact with the Ethereum blockchain and inspired by ethers.js

Ethers For Flutter Ethers is a dart library that connects to interact with the Ethereum blockchain and inspired by ethers.js. Thanks to web3dart which

Hanggi 12 Oct 30, 2022
This is a Flutter project inspired by sustainability and powered by the community

This is a Flutter project inspired by sustainability and powered by the community. TrashTrack is a demo of a social platform with geolocation features that brings people a new way of collaboration.

David 0 Oct 31, 2021
Dependency Injection oversimplified. Inspired by Koin, with focus on scopes.

Dependency Injection oversimplified. Inspired by Koin, with focus on scopes. Features Define your dependencies in a syntax as close to DSL as possible

TamΓ‘s Barta 1 Dec 5, 2022
Chopper is an http client generator using source_gen and inspired from Retrofit.

Chopper Chopper is an http client generator for Dart and Flutter using source_gen and inspired by Retrofit. Documentation Installation Please refer to

Hadrien Lejard 632 Dec 31, 2022
Releases for the Delta-y app: A scrum-inspired personal productivity app for data-nerds with goals

Delta-y Releases This repository contains the public releases for the Delta-y app, which is currently closed source. Resources delta-y-flyer.pdf Video

Delta-y 2 Dec 10, 2021
Modern and elegant test framework for Flutter, inspired by Cypress

flutter_modern_test: Modern, elegant and productive test framework for Flutter, inspired by Cypress GitHub: https://github.com/fzyzcjy/flutter_modern_

fzyzcjy 14 Oct 19, 2022
Medikkare is a doctor appointment app. Written in Flutter. Inspired by Dribbble.

Medikkare is a doctor appointment app. Written in Flutter. Inspired by Dribbble.

Hyunjae Park 76 Jan 1, 2023
Pet Adoption App concept built with Flutter inspired by Aman UX

?? Adopt Me ?? Pet Adoption App concept built with Flutter inspired by Aman UX.

martinoyovo 38 Dec 8, 2022
A Dart library for creating a Dart object to represent directory trees.

Directory Tree A Dart library for creating a Dart object to represent directory trees. Getting Started Import and initialize package import 'package:d

Chiziaruhoma Ogbonda 5 Dec 1, 2021
A type-safe command-line parsing library for Dart

plade Plade is a type-safe CLI parsing library for Dart. Highlights Fully type-safe and null-safe. Support for a variety of different parsing styles (

Ryan Gonzalez 6 Jan 1, 2022
Agent library for Internet Computer, in Dart

agent_dart An agent library built for Internet Computer, a plugin package for dart and flutter apps. Developers can build ones to interact with Dfinit

null 87 Dec 31, 2022
ThingsBoard PE API client library for Dart developers.

ThingsBoard PE API client library for Dart developers. It's compatible with TB PE 3.3.0. Usage A simple usage example: import 'package:thingsboard_pe_

ThingsBoard - Open-source IoT Platform 45 Sep 28, 2022
An equation solving library written purely in Dart.

An equation solving library written purely in Dart Thanks to the equations package you will be able to solve numerical analysis problems with ease. It

Alberto 43 Dec 27, 2022
A Dart library with a solution to use smart enums

Smart Enums Author: Jop Middelkamp A package that can help you create 'smarter' enums that could be extended with some domain logic. Usage final bestF

Jop Middelkamp 2 Oct 1, 2022
Bosun is a library for building organized command line applications in Dart.

Bosun A library for parsing CLI input and structuring CLI commands Features Structure CLI commands in a nice, uniform fashion. Parse args and flag inf

null 3 Oct 13, 2022
A fast and space efficient library to deal with data in Dart, Flutter and the web.

Dart Data Dart Data is a fast and space efficient library to deal with data in Dart, Flutter and the web. As of today this mostly includes data struct

Lukas Renggli 14 Nov 4, 2022
A simple DLNA DMC library implemented by Dart.

DLNA-Dart A simple DLNA DMC library implemented by Dart. It is tiny and only the basic network video casting function is supported. Structure Flutter

Ning 68 Jan 4, 2023