Search code examples
javamockitoenterprise

Mockito exceptions: where is my reasoning incorrect?


I'm using Mockito(1.10.19) within Eclipse mars 2.0 for Java EE testing to test an offline repository. This class relies on an InitialData class to retrieve information.

My first task is to add an address to the initialData list. Here is the method alongside the class and imports:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import com.qa.smurf.InitialData;
import com.qa.smurf.entities.Address;
import com.qa.smurf.repositories.offline.AddressRepositoryOffline;

import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class)
public class AddressRepositoryOfflineTest extends TestCase {
    @Test
    public void testPersistAddress() {
        Address newAddress = new Address("a", "a");
        ArrayList<Address> addList = new ArrayList<Address>();
        addList.add(newAddress);

        AddressRepositoryOffline aro = Mockito.mock(AddressRepositoryOffline.class);
        InitialData initialData = Mockito.mock(InitialData.class);
        Mockito.when(initialData.getAddresses()).thenReturn(addList);
        assertEquals(newAddress, aro.getAddresses().get(0));
    }
}

Which should call AddressRepositoryOffline class getAddresses() method which subsequently calls the InitialData class's getAddresses() method and return the addList ArrayList.

public class AddressRepositoryOffline implements AddressRepository {
    @Override
    public ArrayList<Address> getAddresses() {
        return initialData.getAddresses();
    }
}

public class InitialData {
    public ArrayList<Address> getAddresses() {
        return this.addresses;
    }
}

I then run into the following errors:

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangecheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at OfflineRepository.AddressRepositoryOfflineTest.testPersistAddress(AddressRepositoryTest.java:37)

Line 37 in question is

assertEquals(newAddress, aro.getAddresses().get(0));

with some more errors to do with JUnit and MockitoJUnitandHigherRunnerImpl

Clearly I am misunderstanding how to correctly implement Mockito here. Could somebody help me out?

Many thanks,


Solution

  • Your mocks are not injected into tested class AddressRepositoryOffline

    Try this:

    @RunWith(MockitoJUnitRunner.class)
    public class AddressRepositoryOfflineTest extends TestCase {
    
    @Mock
    private InitialData initialData;
    
    @InjectMocks
    private AddressRepositoryOffline aro; 
    
    @Test
    public void testPersistAddress() {
        Address newAddress = new Address("a", "a");
        ArrayList<Address> addList = new ArrayList<Address>();
        addList.add(newAddress);
    
        Mockito.when(initialData.getAddresses()).thenReturn(addList);
        assertEquals(newAddress, aro.getAddresses().get(0));
    }
    }