Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How does RETURNS_SMART_NULLS affect Mockito's behavior with nulls


How does RETURNS_SMART_NULLS affect Mockito's behavior with nulls


**RETURNS_SMART_NULLS in Mockito is a feature designed to handle null values returned by unstubbed methods more elegantly. Instead of returning a plain `null`, Mockito returns a SmartNull object when this feature is enabled. Here's how it affects Mockito's behavior with nulls:

Purpose of SmartNull

- Avoiding NullPointerException: When you call a method on an object returned by an unstubbed method, Mockito typically returns `null`, leading to a `NullPointerException` if you try to use that object. SmartNull helps by providing a clearer exception message, indicating where the unstubbed method was called, which aids in debugging[1][5].

Behavior with SmartNull

- Exception Handling: Although SmartNull does not prevent `NullPointerExceptions`, it provides a more informative stack trace. This helps developers quickly identify the line of code where an unstubbed method was invoked, making it easier to fix the issue by properly stubbing the method[1][5].

- Default Strategy in Mockito 4: There is a proposal to make RETURNS_SMART_NULLS the default return strategy in Mockito 4, which would enhance the debugging experience by providing more detailed error messages for unstubbed methods[1][8].

Usage

To use RETURNS_SMART_NULLS, you can create a mock object with this answer strategy:

java
SomeObject object = Mockito.mock(SomeObject.class, Mockito.RETURNS_SMART_NULLS);

This ensures that any unstubbed method calls on `object` will return SmartNull instead of `null`, helping you identify unstubbed methods more effectively.

Conclusion

**RETURNS_SMART_NULLS is a valuable feature in Mockito for managing nulls returned by unstubbed methods. It enhances the testing experience by providing clearer error messages, which can significantly reduce debugging time. However, it does not eliminate the need to properly stub methods; it merely makes it easier to identify when stubbing is missing.

Citations:
[1] https://wesome.org/mockito-3-answere-returns-smart-nulls
[2] https://groups.google.com/g/mockito/c/efQb_um8WeY
[3] https://www.damirscorner.com/blog/posts/20221223-MockitoAndNonNullTypesInKotlin.html
[4] https://community.esri.com/t5/arcgis-pro-ideas/specify-how-nulls-are-sorted-in-the-attribute/idi-p/1184709
[5] https://www.toptal.com/java/a-guide-to-everyday-mockito
[6] https://stackoverflow.com/questions/32841543/matchers-any-for-null-value-in-mockito
[7] https://github.com/dart-lang/mockito/blob/master/NULL_SAFETY_README.md
[8] https://github.com/mockito/mockito/issues/2460
[9] https://blog.pchudzik.com/201909/mockito-answers/
[10] https://stackoverflow.com/questions/30918506/mockito-returns-smart-nulls-answer-weird-behavior
[11] https://contributors.scala-lang.org/t/mockito-testing-nulls-and-exceptions/3915