Search code examples
unit-testingdarttestingmockitoprivate-methods

Dart: testing private methods by accessing mock's property


I'm trying to get a mocked object property. During the initialization, 'child' class is getting a reference to a parent's private function. I'd like to catch this reference during testing to check parent's private method.

This is a simplified example of much more complex code:

class Monkey{

final name;
final Perk _perk;


Monkey('Maya', this._perk){
this._perk.jump = this._jump;
  }

void _jump(int a){ // here's the problem, not able to test private method
print('jump ${a}');
  }

}

All I want to do is to be able to test private method _jump during testing in mockito. I don't want to change the code. During test I created

class MockPerk extends Mock implements Perk{}
Monkey(mockedPerk);

What I want to achieve is:

  1. Create Monkey instance with mockedPerk
  2. Capture property _perk.jump in MockedPerk class
  3. Get reference to private _jump method of Moneky's class to be able to test it.

Limitation

  1. Making method public is not an option.
  2. Making method public with @visibleForTesting is not an option

Solution

  • You can capture values passed to setters with verify(mock.setter = captureAny). For example:

      var mockedPerk = MockPerk();
      var monkey = Monkey('Maya', mockedPerk);
      var jump = verify(mockedPerk.jump = captureAny).captured.single as void
          Function(int);
      jump(5); // Prints: jump 5