Search code examples
dartdart-unittest

How to write tests using the service scope


My app is accessing object from the service scope (package:gcloud/service_scope.dart), like the storageService and additional services that I put inside the scope with ss.register().

Now I want to unit test a function that accesses this scope, and uses mock objects that I want to put in the service scope.

Is the only way to do so, to register them for every test, like this:

var withServiceScope = (callback()) => ss.fork(() {
  // Register all services here
  return callback();
});
test('the description', () => withServiceScope(() async {
  // Call my function that can now access the service scope
}));

Or is there are way that allows me to do that in the setUp() function so I don't need to add this line for each test?


Solution

  • This might make it simpler to write your tests (code not tested)

    import 'package:test/test.dart' as t;
    import 'package:test/test.dart' show group;
    
    var withServiceScope = (callback()) => ss.fork(() {
      // Register all services here
      return callback();
    });
    
    test(String description, Function testFunction) {
      t.test(description, () => withServiceScope(() async {
        testFunction();
      }));
    }
    
    main() {    
      test('the description', () async {
        // Call my function that can now access the service scope
      }));
    }