gpt4 book ai didi

java - 使用 Mockito 进行模拟

转载 作者:行者123 更新时间:2023-11-30 06:52:04 25 4
gpt4 key购买 nike

我正在尝试编写Mockito测试用例来获取plantIDs并执行一些处理。我也添加了测试用例。

这是我的测试用例

@RunWith(MockitoJUnitRunner.class)
public class PlantDetailsServiceTest {
@InjectMocks PlantDetailsService service;
@Mock PlantDetailsHelper helperMock;
@Mock HttpURLConnection conn;
@Mock BufferedReader buf;
@Mock InputStream input;
@Mock InputStreamReader ir;
@Mock JSONObject json;
@Mock JSONArray arr;
@Mock List<String> plantResult;


@Test
public void TestGetPlantDetails() throws Exception
{
String plantID1= "23";

List<String> plantResult = new ArrayList<String>();
plantResult.add(plantID1);
Mockito.when(helperMock.getPlantIds()).thenReturn(plantResult);
URL url = new URL("**********/23");
conn=(HttpURLConnection)url.openConnection();
Mockito.when((HttpURLConnection)url.openConnection()).thenReturn(conn);
Mockito.when(conn.getResponseCode()).thenReturn(200);
input=conn.getInputStream();
Mockito.when(conn.getInputStream()).thenReturn(input);
ir=new InputStreamReader(input);
Mockito.when(new InputStreamReader((conn.getInputStream()))).thenReturn(ir);
buf=new BufferedReader(ir);
Mockito.when(new BufferedReader(new InputStreamReader((conn.getInputStream())))).thenReturn(buf);
String output=buf.readLine();
Mockito.when(buf.readLine()).thenReturn(output);
json=new JSONObject(output);
Mockito.when(new JSONObject(output)).thenReturn(json);
arr=json.getJSONArray("Data");
Mockito.when(json.getJSONArray("Data")).thenReturn(arr);
assertThat(output,is(notNullValue()));
List<PlantDetailsDTO> plantDetailsList=new ArrayList<PlantDetailsDTO>();
plantDetailsList=service.getPlantDetails();

}
}

这会在我读取 InputStream() 的行中引发错误。我无法打开连接,因为 URL 可能是最终类。我也在 openConnection() 行中收到错误。缺少方法调用。

最佳答案

我认为您忘记添加两个配置详细信息之一,这将启用注释模拟:

@RunWith(MockitoJUnitRunner.class)
public class PlantDetailsServiceTest {

@Before
public void init(){
MockitoAnnotations.initMocks(this);
}

没有这些,mockito 不会实例化 @Mock,因此你会得到空指针异常。

关于java - 使用 Mockito 进行模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42551711/

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