0
我正在Eclipse Mars 2.0中使用Mockito(1.10.19)進行Java EE測試以測試脫機版本庫。該類依賴InitialData類來檢索信息。Mockito異常:我的推理在哪裏不正確?
我的第一個任務是將一個地址添加到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類的getAddresses()方法,並返回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。有人能幫我嗎?
非常感謝,
太謝謝你了。 – shirafuno