Mockito lenient() when to use

17,355

Solution 1

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.

Solution 2

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.

Solution 3

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.

Share:
17,355
htafoya
Author by

htafoya

Technology officer and architect, with a solid trajectory as a mobile engineer developing apps with more than 50 million users. My main experience comes from Android and iOS apps and their whole ecosystem; this is, mobile architecture and how they interact with OS, servers, CDNs, databases, statistics, advertising, notifications, UX, design principles, security, etc. My favorite languages and experiences come from Kotlin, Swift, Java, Javascript and Web Technologies. I also have non specialized knowledge on other general technology topics; I also like to keep track on what's going on out there. If I would describe myself on StackOverflow, is that I like to investigate and test thoroughly before asking any question, thus I have a relative low accept rate or badge xp, most of my questions offer new knowledge and many times they are answered by myself after I find a working solution, if none is provided by someone else. That is, points (XP) are fun but I do not care very much for that, I'm here to help expand the knowledge of my favorite techs, to learn and overall help myself and others understand how things work and build better products. I'm glad to help when I am able to or when I find new answers to solved problems.

Updated on August 16, 2022

Comments

  • htafoya
    htafoya almost 2 years

    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?