Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning when mocking a class

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?

like image 222
user3154375 Avatar asked Jan 02 '26 00:01

user3154375


2 Answers

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.

like image 94
Shailen Tuli Avatar answered Jan 06 '26 04:01

Shailen Tuli


You can silence the warnings if you implement noSuchMethod()

class MockFoo extends Mock implements Foo {
  noSuchMethod(Invocation invocation) {
    return super.noSuchMethod(invocation);
  }
}
like image 34
Günter Zöchbauer Avatar answered Jan 06 '26 06:01

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!