2

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
Ensei Tankado
  • 270
  • 2
  • 12

1 Answers1

1

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
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • This is exactly what I want to achieve. Thanks a lot for your rapid support. I played with arguments capturing before but I was not aware to use it this way. – Ensei Tankado Apr 20 '21 at 09:02
  • How to capture setter values is not documented very well. I had to look at `package:mockito`'s unit tests to see examples for how to do it. Also, if this answered your question, don't forget to accept it. – jamesdlin Apr 20 '21 at 09:14
  • I would also like to ask how can I detect if any function have been called inside of non mocked class? Is it possible? – Ensei Tankado Apr 21 '21 at 07:20
  • In general, you can't. You would need to have the class use callbacks instead of invoking the function directly ("dependency inversion/injection"). – jamesdlin Apr 21 '21 at 07:25