Mockito mock object using real implementation

Why is mockMap using a real implementation? How to prevent this?

In the testFirstKeyMatch method

 when(mockMap.keySet().toArray()[0])... 

throws ArrayIndexOutOfBoundsException: 0 when starting the test.

MaxSizeHashMap is a LinkedHashMap with a maximum size of 7, throws an IndexOutOfBoundsException when I try to add more.

A profile is tracking something that is not essential to this.

SuperClass.java

 public class SuperClass { protected String[] days; protected MaxSizeHashMap<String, String> map; public SuperClass() { days = new String[7]; map = new MaxSizeHashMap<String, String>(); //... } void updateDays() { cal = Calendar.getInstance(); for (int i = 0; i < 7; i = i + 1) { //adds short names "Mon", "Tue", ... to days days[i] = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US); cal.add(Calendar.DATE, 1); } } void firstKeyMatch(Profile profile) { updateDays(); //checks if first key of map is not same as days[0] if (days[0] != map.keySet().toArray()[0]) { profile.add(); //... } } } 

SuperClassTest.java

 @RunWith(MockitoJUnitRunner.class) public class SuperClassTest { @InjectMocks private SuperClass spr = new SuperClass(); @Mock private MaxSizeHashMap<String, String> mockMap; @Mock private Profile mockProfile; //... @Test public void testFirstKeyMatch() { when(mockMap.keySet().toArray()[0]).thenReturn(spr.days[0]); verify(mockProfile, never()).add(); } } 
+5
source share
2 answers

According to the documentation , the implicit mockito behavior for the layout should return the default values .

By default, for all methods that return a value, the layout will return either a null value, or a primitive / primitive wrapper value, or an empty collection, if necessary. For example, 0 for int / Integer and false for boolean / Boolean.

As a result, your mockMap.keySet() will return an empty hash set, which then converts to an empty array and tries to extract the (non-existent) first element, therefore, IOOBE.

debugger

In conclusion, mockito does not use the actual implementation, but behaves normally as intended.

You did not publish the entire SuperClass constructor, but probably after you create the map, you will also fill it with values. If this is true, then it can be argued that the exception is actually proof that mockito is not using a real implementation, because you really get the first element.

As for solutions, it has already been proposed to return your own hash set with any data that you need (loans go to Abubakkar):

 when(mockMap.keySet()).thenReturn(new HashSet(Arrays.asList("your day string"))); 
+3
source

To redirect all calls to mockMap.keySet().toArray()[i] to spr.days[i] , you can tell mockMap to return the days array when someone requests a key set.

 Set keySetMock = mock(Set.class); when(keySetMock.toArray()).thenReturn(spr.days); when(mockMap.keySet()).thenReturn(keySetMock); 
+1
source

Source: https://habr.com/ru/post/1270022/


All Articles