mercredi 6 janvier 2021

How to mock methods by reflection using Mockito

We are trying to mock methods by reflection using Mockito, because we want to create some generic tests, which will be run for any new feature that is requested in our company.

If a new feature is requested by business, after it will be implemented, the developer will need to complete some configuration properties files and by using reflection, some generic unit tests will be automatically run which will be applicable for all the old and new features.

For this reason, we need to be able to mock methods by reflection.

I have seen that there is already this question asked here:

Using Mockito to mock methods by reflection

but the problem is that m.invoke (mockForService, params) is invoking the method and our need is to only have a mock of that method when it will be called.

For example:

A class has a method m1 which will call B class method m2

How would it be possible to mock B.m2 to return a mocked answer by using reflection, because m.invoke (mockForService, params) is directly invoking the method and is throwing an exception.





Aucun commentaire:

Enregistrer un commentaire