0

I am trying to understand how mocking works with dart and mockito. Image I have the below declarations:

void foo(){}

and similarly a class

class BarClass {
   void bar(){}
}

and then my widget accesses the first one directly as foo(); and the second one as BarClass().

What would be the way to mock these two? Should I be accessing them through something like getit to mock them properly or is there actually a way?

Aegletes
  • 460
  • 2
  • 6
  • 17

1 Answers1

0

You can easily mock classes by creating a new class that implements the functionality of your old one using the mockito package

example code:

class MockBarClass extends Mock implements BarClass {}

you can mock methods of your BarClass in the following way:

final mock = MockBarClass();
when(() => mock.boo()).thenAnswer((_) {
    // your mocked response
    print("hello world");
});

you can mock functions that are in no classes the same way:

when(boo()).thenReturn();

source by Remi Rousselet


additional information if you ask yourself what's the difference between .thenReturn(...) and .thenAnswer((){...}):

I recommend reading this explanation: https://stackoverflow.com/a/36627077/12165405 (even though it's for java, the same applies for that flutter package)

Chrissi
  • 189
  • 1
  • 8
  • Yes, I know I can mock classes, but how do you mock a class *or* a global function for a widget test, that was the question. Is there any other way than passing the class/function as a parameter into the widget? – Aegletes May 28 '22 at 18:04
  • 1
    oh okay! That is one downside of using `getIt` instead of `Provider` or something else. But what you can do (without dependency injection) , is to override the registered Service/Class in your `setUpAll` function of your test with a *mocked class*. More information here: https://stackoverflow.com/a/66246565/12165405 . Unfortunately I don't have much experience with this. – Chrissi May 28 '22 at 18:53
  • yep, thank you, I think it's more or less possible with getit but without it is not as far as I understand – Aegletes May 28 '22 at 19:47
  • This is not working – Alexei Vinokur Oct 11 '22 at 14:03