Tuesday, July 24, 2018

New Mockito API: lenient()

Last major feature before version 3.0 is a new "lenient()" method for stubbing (javadoc). We added it it to prepare users for an important change in default Mockito behavior. In version 3.0 (planned for winter '18) stubs will be validated by default. Unused stubs will cause exceptions and fail the test. Argument mismatch in stubbing will fail the test early, too. This way, Mockito will actively help keeping tests cleaner and make you more productive when dealing with stubbing issues.

"Strict stubbing" feature in Mockito is available since early 2.x versions. However, most users stay with the defaults and don't take advantage of the feature. With the next major version of Mockito, we will change the defaults.

In Mockito 3.0 all stubbings will be "strict" and validated. In rare scenarios where the extra validation is unhelpful you can use the new "lenient()" method which is the topic of this post:

//specific stubbing will be lenient:lenient().when(mock.foo()).thenReturn(true);

//all stubbings of the mock will be lenient:Foo mock = mock(Foo.class, withSettings().lenient();

//all stubbings across all mocks of a test class will be lenient:@Rule MockitoRule mockito = MockitoJUnit.rule().strictness(Strictness.LENIENT);


The specific scenario explaining the need for "lenient()" method is documented in our Javadoc. To discuss the feature drop us a comment in ticket #1272.

"lenient()" method is useful today if you already leverage strict stubbing. For more information about strict stubbing check out the earlier blog post or the Devoxx US '17 video presentation.

Use strict stubbing. It will really clean up your tests and help debugging stubbing issues. Let us know how it works for you and keep writing great tests every day!