Warning when mocking a class

189 views Asked by At

I am reading this article - https://www.dartlang.org/articles/mocking-with-dart/ - about mocking wiht Dart and have gotten this simple example working.

import 'package:unittest/mock.dart';

class Foo {
  int x;
  bar() => 'bar';
  baz() => 'baz';
}

class MockFoo extends Mock implements Foo {}

void main() {
  var mockFoo = new MockFoo();
  mockFoo.when(callsTo('bar')).
      thenReturn('BAR');

  print(mockFoo.bar());
}

The code prints 'BAR' correctly, so the mocking clearly works. But the Dart Editor generates a warning/error:

Missing inherited members: 'Foo.bar', 'Foo.baz' and 'Foo.x'

Despite this warning/error, the code seems to work but I would like to get rid of the error. How do I do that?

2

There are 2 answers

0
Shailen Tuli On

Since MockFoo implements Foo, you need to define x, bar() and baz(), even if you are only interested in the behavior of bar(). For your example, this is as simple as doing the following:

class MockFoo extends Mock implements Foo {
  int x;
  bar() {}
  baz() {}
}

For more substantial classes that contain a long list of members, this pattern can become quite tedious, but I don't know a better way of silencing the Editor warning. Hope this helps.

2
Günter Zöchbauer On

You can silence the warnings if you implement noSuchMethod()

class MockFoo extends Mock implements Foo {
  noSuchMethod(Invocation invocation) {
    return super.noSuchMethod(invocation);
  }
}