felangel / mocktail

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

Mock with default stub implementation feature #233

Closed dfdgsdfg closed 3 months ago

dfdgsdfg commented 3 months ago

How about add default stub when define the mock class?

class Cat {
  final Future<String> meow() => repo.getMeow;
}

class MockCat extends Mock implements Cat {
  // Default stub
  final Future<String> meow() => Future.value('meow');
}

final cat = MockCat();

cat.meow(); // return default stub 'meow' from RealCall

when(() => cat.meow()).thenAnswer((_) async => 'grrrrrrr'); // override RealCall

cat.meow(); // return override stub 'grrrrrrr'

Is this possible by any chance?

Work around

class MockCat extends Mock implements Cat {
  McokCat() {
    // as default stub. seems to working well
    // but cat.reset() remove default stub setting below
    when(() => meow()).thenAnswer((_) async => 'meow');
  }
}
felangel commented 3 months ago

If you want to have defaults then I recommend creating a Fake:

import 'package:mocktail/mocktail.dart';

class Cat {
  Future<String> meow() async => 'meow';
}

class FakeCat extends Fake implements Cat {
  @override
  Future<String> meow() async => 'default meow';
}

void main() async {
  final cat = FakeCat();

  print(await cat.meow()); // default meow
}

Hope that helps! Closing for now đź‘Ť

xiprox commented 2 months ago

Hi. From what I can tell, it is not possible to later override the behavior of a Fake with when. I'm wondering if I could define a Fake/Mock class with default behavior, then override some of that only where necessary. For example, a repo that returns empty data unless overriden.

felangel commented 2 months ago

Hi. From what I can tell, it is not possible to later override the behavior of a Fake with when. I'm wondering if I could define a Fake/Mock class with default behavior, then override some of that only where necessary. For example, a repo that returns empty data unless overriden.

If you really want to do that then you can add the stubs in the mock class’s constructor body or create a helper function that constructs the mock instance and stubs the default methods.