Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito lenient() when to use

As I understand, lenient silences the exceptions thrown by StrictStubbing. Based on this, lenient shouldn't be used, maybe only temporary while doing TDD, because strict stubbing exceptions would generally mean that your code is either wrong, test is badly designed or you are adding unnecessary lines.

Is there a practical scenario where lenient is actually needed or useful for the test?

like image 727
htafoya Avatar asked Feb 26 '20 18:02

htafoya


3 Answers

For example, it's very useful while migrating from Mockito 1 to Mockito 2 (the latter introduced strict stubbing), if you need to do it in a short period of time.

like image 156
amseager Avatar answered Oct 07 '22 14:10

amseager


Strict Stubbing is introduced to detect unnecessary stubs and write a much cleaner test. If you are getting exceptions, focus should be on improving test cases and not to by-pass strict stubbing check.

like image 31
pinaci Avatar answered Oct 07 '22 14:10

pinaci


I just came across an unusual valid use for this. We made a code change which disabled a feature by default (prior to taking it out altogether in a future release). We needed a test that the disabling actually worked, so we needed to mock some flag as false. However, we also needed to mock a few other values becaues, if the bit of code to disable the feature (which tested that flag) got broken somehow, the default settings for the feature would cause it to do nothing anyway, so we wouldn't be able to observe failure of the flag.

To summarise: in the success case, we would get UnnecessaryStubbingException with the mocking but, without it, the failure case wouldn't actually fail. Hence we marked those specific mockings as lenient.

like image 22
HughG Avatar answered Oct 07 '22 14:10

HughG