Home > OS >  Dart Mockito - stub a field
Dart Mockito - stub a field

Time:06-26

Using mockito

  group("VgnItmFormEvents", () {
    setUp(() {
      mockStore = MockManageVgnItmStore();
      when(mockStore.formType).thenReturn(const Edit());// if I leave this line out I get missing stub error
})

This test fails:

test('OnNameChanged', () async {
  mockStore.formType = Add(name: 'add');
  expect(mockStore.formType, Add(name: 'add'));
});

The line with the code comment is the culprit, but without it, I get a missing stub error. How do I make the mock have mockStore.formType as a settable field that I can check what it was set to?

This is the actual field on the real object:

  FormType get formType => stateNotifiersVm.formType;
  set formType(FormType formType) =>
      stateNotifiersVm.formTypeStateNotifier.setState(formType);

This is the stateNotifiersVm:

  FormType get formType => _formType;
  set formType(FormType formType) => formTypeStateNotifier.setState(formType);

CodePudding user response:

You can verify if a setter was called with a specific value without having to call the getter (and thus hitting the missing stub error):

@GenerateMocks([Cat])
import 'cat.mocks.dart';

class Cat {
  int _formType = 0;

  int get formType => _formType;
  set formType(int ft) => _formType = ft;
}

void main() {
  final cat = MockCat();

  test('can set formType', () {
    cat.formType = 8;
    verify(cat.formType = 8);
  });
}

Is this what you were looking for? Sadly mockito does not have a way to call the "real" method underneath as far as i know.

  • Related