felangel / mocktail

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

Mock or skip void method and global method #231

Closed Ram-CGPL closed 3 months ago

Ram-CGPL commented 4 months ago

Sometime i want to mock global method and void method so that i can bypass or skip it.

felangel commented 3 months ago

Hi @Ram-CGPL 👋 Thanks for opening an issue!

The issue with global methods is precisely that they are difficult to mock/test. I recommend injecting your global method into the classes/methods that you're testing so that you can mock it. For example:

Rather than calling the global method directly like this:

// Global Method
int sum(int x, int y) => x + y;

int foo() {
  return sum(1, 2);
}

You can inject it like so:

// Global Method
int sum(int x, int y) => x + y;

int foo({int Function(int x, int y) sum = sum}) {
  return sum(1, 2);
}

And then you can inject whatever you want in your tests:

int testSum(int x, int y) => 42;

test('...', () {
  expect(foo(sum: testSum), equals(42));
});

Hope that helps 👍