Mockito例外:我的推理哪里不正确



我在Eclipse mars 2.0中使用Mockito(1.10.19)进行Java EE测试,以测试离线存储库。此类依赖InitialData类来检索信息。

我的第一个任务是在initialData列表中添加一个地址。下面是类和导入旁边的方法:

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));
    }
}

它应该调用AddressRepositoryOffline类的getAddresses()方法,该方法随后调用InitialData类的getAddress()方法并返回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;
    }
}

然后我遇到了以下错误:

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)

有问题的第37行是

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

还有一些错误与JUnit和MockitoJUnitandHigherRunnerImpl 有关

很明显,我误解了如何在这里正确地实现Mockito。有人能帮我吗?

非常感谢,

您的mock没有注入测试类AddressRepositoryOffline

试试这个:

@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));
}
}

相关内容

  • 没有找到相关文章

最新更新