-6ren">
gpt4 book ai didi

java - 带有mockito和多个返回值的模拟CSV阅读器

转载 作者:行者123 更新时间:2023-12-02 05:05:26 25 4
gpt4 key购买 nike

我不想 mock CSVReader。所以我的模拟应该每次返回一个新数组,这应该是通用的。最后一个值应该为空。

例如

nextLine() -> ["a","b","c"]
nextLine() -> ["a","b","c"]
nextLine() -> null

我的模拟类:

import au.com.bytecode.opencsv.CSVReader;
import com.sun.javafx.beans.annotations.NonNull;
import org.mockito.Mockito;
import org.mockito.stubbing.OngoingStubbing;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class CSVReaderMock {
CSVReader reader;
private boolean linesCorrectInitialized;

public CSVReaderMock()
{
reader = mock(CSVReader.class);
}

public CSVReaderMock returnLines(@NonNull List<String> lines) {
// the last value has to be null
lines.add(null);
try {
for (String line : lines) {
String[] lineArr = null;
if (line != null) {
lineArr = line.split(",");
}
when(reader.readNext()).thenReturn(lineArr);
}
linesCorrectInitialized = true;
} catch (IOException e) {
e.printStackTrace();
};
return this;
}

public CSVReader create() {
if (!linesCorrectInitialized) { throw new RuntimeException("lines are not initialized correct"); }
return reader;
}

}

这里是一个测试用例(我只是写来检查我的模拟构建器):

@Test
public void testImportLines() throws Exception {
CSVReader reader;
List<String> list = new LinkedList<>();
list.add("some,lines,for,testing");
reader = new CSVReaderMock().returnLines(list).create();


System.out.println(reader.readNext()); // should return [Ljava.lang.String;@xxxx with conent-> ["some","lines","for","testing"]
System.out.println(reader.readNext()); // should return null
}

实际输出是:

null
null

所以我的问题是,如何在不事先知道列表外观的情况下传递返回值列表?我知道我可以通过 .thenReturn(line1,line2,line3) 传递“csv 行”,但这会破坏我的方法。

最佳答案

Mockito 有一个 ReturnsElementsOf就在这样的场合回答。

Returns elements of the collection. Keeps returning the last element forever. Might be useful on occasion when you have a collection of elements to return.

所以现在您只需要准备元素,然后将其传入。因为需要在最后添加 null 调用,所以它会阻止您重用 CSVReaderMock 构建器,但无论是否这样做都是一样的你使用答案。

List<String[]> returnList = new ArrayList<>();

public CSVReaderMock returnLines(@NonNull List<String> lines) {
try {
for (String line : lines) {
String[] lineArr = null;
if (line != null) {
lineArr = line.split(",");
}
returnList.add(lineArr);
}
linesCorrectInitialized = true;
} catch (IOException e) { /* ... */ };
return this;
}

public CSVReader create() {
if (!linesCorrectInitialized) { /* ... */ }
// Return null repeatedly after all stubs are exhausted.
returnList.add(null);
when(reader.readNext()).thenAnswer(new ReturnsElementsOf(returnList));
return reader;
}

关于java - 带有mockito和多个返回值的模拟CSV阅读器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27836956/

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