d-loose / testing-workshop

GNU General Public License v3.0
0 stars 0 forks source link

Late variable + setUp vs. builder method for mocks #1

Open jpnurmi opened 1 year ago

jpnurmi commented 1 year ago

When setting up mocks for increasing amounts of tests, one usually needs to parameterize the mock instance somehow or set up different variants. At that point, a single late-initialized mock instance often becomes a limitation. While you could use test groups to share certain set-up routines between similar tests, it gets more confusing than a parameterized builder method.

void main() {
  late TaskList taskList;

  setUp(() {
    taskList = MockTaskList();
    when(...).thenFoo(...);
  });

  test('...', () {
    ...
  });
}

vs.

void main() {
  TaskList createTaskList(List<Task> tasks) {
    final taskList = MockTaskList();
    when(...).thenFoo(...);
    return taskList;
  }

  test('...', () {
    final taskList = createTaskList(...);
    ...
  });
}

Based on the experience from the older UDI tests that use the former approach, I'd highly recommend the latter approach instead because it's much easier to introduce new tests with slightly different mocking needs. :)

d-loose commented 1 year ago

Thanks, this is very valuable advice. I won't change the skeleton for the exercise though, since I want the participants to think about the when() statement for themselves for a second. But I'll keep the issue open and refer to it during the workshop :)