gpt4 book ai didi

java - Mockito异常: where is my reasoning incorrect?

转载 作者:行者123 更新时间:2023-12-01 09:56:22 29 4
gpt4 key购买 nike

我在 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类的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。有人可以帮我吗?

非常感谢,

最佳答案

您的模拟不会注入(inject)到测试类 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));
}
}

关于java - Mockito异常: where is my reasoning incorrect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37184086/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com