3

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?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567

2 Answers2

1

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.

Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51
1

You can silence the warnings if you implement noSuchMethod()

class MockFoo extends Mock implements Foo {
  noSuchMethod(Invocation invocation) {
    return super.noSuchMethod(invocation);
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Doing this, you may also want to apply the `@proxy` annotation. Since the Mock class defines noSuchMethod, just appending the `@proxy` annotation to your class _should_ prevent warnings however this doesn't seem to be the case in the latest dev build. – Matt B Jan 02 '14 at 19:33
  • Thanks @MattB for starting a discussion about that topic on the Dart mailing list where Brian Wilkerson provided an extended explanation [Should `@proxy` suppress noSuchMethod warnings if extending a class which implements noSuchMethod?](https://groups.google.com/a/dartlang.org/forum/#!topic/editor/GIt4ONo7t7E) – Günter Zöchbauer Jan 03 '14 at 06:46