mocktail icon indicating copy to clipboard operation
mocktail copied to clipboard

Unable to mock functions with functions as argument

Open Avendo07 opened this issue 2 years ago • 1 comments

Describe the bug Unable to mock and/or verify functions which take in function/callback as an argument

Reproducible Code

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

class MockMockableClass extends Mock implements MockableClass {}

class MockableClass {
  bool inputCallback(bool Function() query) {
    bool val = query();
    return (!val);
  }
}

class TestClass {
  bool hello(MockableClass mockClass) {
    bool val = mockClass.inputCallback(() => true);
    return val;
  }
}

void main() {
  late MockMockableClass mockMockClass;
  mockMockClass = MockMockableClass();
  test("test for mocktail", () {
    when(() => mockMockClass.inputCallback((() => true))).thenReturn(false);
    TestClass testClass = TestClass();
    bool val = testClass.hello(mockMockClass);
    expect(val, false);
  });
}

Expected behavior The above code shows "type 'Null' is not a subtype of type 'bool'". Whereas it should have mocked the function. This works if I replace the function (i.e. () => true) with "any()", but then I am unable to verify if this function was triggered or not.

Am I doing something wrong or is there a workaround to mock the function and verify if the "inputCallback" function was triggered or not.

Avendo07 avatar Aug 26 '22 10:08 Avendo07

i have a same type of situation , i tried both mocktail and mokito both of it does not work https://github.com/felangel/mocktail/issues/157

rddewan avatar Oct 12 '22 01:10 rddewan

You can use the any matcher in this case:

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

class MockMockableClass extends Mock implements MockableClass {}

class MockableClass {
  bool inputCallback(bool Function() query) {
    final val = query();
    return !val;
  }
}

class TestClass {
  bool hello(MockableClass mockClass) {
    final val = mockClass.inputCallback(() => true);
    return val;
  }
}

void main() {
  late MockMockableClass mockMockClass;

  setUp(() {
    mockMockClass = MockMockableClass();
  });

  test('test for mocktail', () {
    when(() => mockMockClass.inputCallback(any())).thenReturn(false);
    final testClass = TestClass();
    final val = testClass.hello(mockMockClass);
    expect(val, false);
  });
}

Closing for now, hope that helps!

felangel avatar Apr 20 '24 03:04 felangel