Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocked List using Mockito isEmpty always returns false, even if the size is 0

I'm playing with Mockito (1.9.5) and stuck at first simple test case:

List mockedList = mock(ArrayList.class);
assertEquals(0, mockedList.size()); // Passed
assertTrue(mockedList.isEmpty()); // Failed

Can anyone explain why isEmpty() here returns false while the size() returns 0?

like image 567
Genzer Avatar asked Jun 15 '12 10:06

Genzer


People also ask

How do you mock a list of objects?

We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.

What does mock in Mockito do?

The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called. We don't need to do anything else to this method before we can use it.

How do you call a real method on mocked object?

Mockito allows us to partially mock an object. This means that we can create a mock object and still be able to call a real method on it. To call a real method on a mocked object we use Mockito's thenCallRealMethod().

What is difference between @mock and Mockito mock?

Difference between @Mock and @InjectMocks In mockito-based junit tests, @Mock annotation creates mocks and @InjectMocks creates actual objects and injects mocked dependencies into it. Use @InjectMocks to create class instances that need to be tested in the test class.


1 Answers

I think this happens because mockito doesn't know the semantic meaning of isEmpty() and when it encounters a boolean method mocks it with a default value that is false. Same think happens with size() but the default value here is 0.

Basically, you need to define the expected behaviour of your mocked object. If you don't, it will return default values.

like image 50
bruno conde Avatar answered Sep 25 '22 05:09

bruno conde