Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Mockito RETURNS_DEFAULT return a default String?

Tags:

java

mockito

In the following example (mockito 1.10.19):

    MyClass myClass = Mockito.mock(MyClass .class, RETURNS_DEFAULTS);
    String s = myClass.getName();

Why does this result in s == null rather than an empty String?

It indeed promised null for a String in ReturnsEmptyValues. But it seems so obvious to return "" that I'm wondering if there is a reason for it not to.

EDIT: updated version to 1.10.19 from 1.8, because no documentation is available anymore for 1.8.

like image 470
Thirler Avatar asked Dec 22 '11 13:12

Thirler


People also ask

How does Mockito@ mock work?

Simply put, Mockito works by storing and retrieving method invocation details on mocks using method interception. Method interception is a technique used in Aspect Oriented Programming(AOP) to address cross-cutting concerns in a software system like logging, statistics etc., by intercepting method calls.

How to mock response in Mockito?

With Mockito, you create a mock, tell Mockito what to do when specific methods are called on it, and then use the mock instance in your test instead of the real thing. After the test, you can query the mock to see what specific methods were called or check the side effects in the form of changed state.

How to mock any method in Mockito?

In this case you're setting the default behaviour of your mocked object. In fact, if you call doReturn(...). when() you'll override this default behaviour with new custom stub. So it's useful if you need to change the behaviour of one method while others will still return the defaults.


1 Answers

From the link you posted;

Default answer of every Mockito mock.

  • Returns appropriate primitive for primitive-returning methods
  • Returns consistent values for primitive wrapper classes (e.g. int-returning method retuns 0 and Integer-returning method returns 0, too)
  • Returns empty collection for collection-returning methods (works for most commonly used collection types)
  • Returns description of mock for toString() method
  • Returns null for everything else

From the FAQ:

What values do mocks return by default?

In order to be transparent and unobtrusive all Mockito mocks by default return 'nice' values. For example: zeros, falseys, empty collections or nulls.

It was probably done to stay consistent with any other methods which return null for any other non-collection, non-primitive Wrapper objects.

You can always implement your own Answer to pass to mock which returns empty strings for String returning methods.

like image 56
Tom Tresansky Avatar answered Oct 30 '22 15:10

Tom Tresansky