问题描述
我试图第一次使用jmockit测试我的Java代码,我真的很困惑。我有一个读取文件并返回从文件中读取的字符串行作为列表的方法。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Reader {
public static final int LIMIT = -1;
public static final int EMPTY_FILE = 0;
private String delimiter = ",";
public Reader() {}
public List<List<String>> readFile(String fileName,String delimiter) throws IOException {
List<List<String>> rawData = new ArrayList<>();
File input = new File(fileName);
if (!delimiter.isEmpty())
this.delimiter = delimiter;
if (input.length() == EMPTY_FILE) {
throw new IOException("File is empty. Check file and try again.");
}
BufferedReader reader = new BufferedReader(new FileReader(input));
String line;
while ((line = reader.readLine()) != null) {
List<String> lineData = Arrays.asList(line.split(this.delimiter,LIMIT));
rawData.add(lineData);
}
return rawData;
}
}
我正在尝试使用模拟阅读器和bufferedReader测试此代码,但没有任何运气。显然我做错了,但我不知道该怎么做。
我想要的是创建一个模拟文件,该文件将被读取并像空文件或非空文件一样对其进行测试。
到目前为止我已经尝试过:
class ReaderTest {
static final String FILENAME = "input.txt";
@Injectable
File mockedFile;
@Mocked
BufferedReader mockedBufferedReader;
@Mocked
FileReader mockedFileReader;
@Test
void readNonEmptyInputFileShouldDonothing() throws FileNotFoundException {
new Expectations(File.class) {{
new File(anyString);
result = mockedFile;
}};
new Expectations(BufferedReader.class) {{
new FileReader(anyString);
result = mockedFileReader;
new BufferedReader(mockedFileReader);
result = mockedBufferedReader;
}};
Reader reader = new Reader();
Assertions.assertDoesNotthrow(() ->
reader.readFile(FILENAME,FieldsConstants.DELIMITER));
}
}
此测试给我一个IllegalArgumentException错误:
Invalid Class argument for partial mocking (use a MockUp instead): class java.io.File
解决方法
我设法使用PowerMock和EasyMock API解决了我的问题。我遇到的唯一问题是,一开始我使用的是Junit5,而PowerMock并未按预期工作。我切换到Junit4,一切都很好。如果有人感兴趣,请提供一些示例代码:
Realm.init(this)
val config = RealmConfiguration.Builder()
.build()
Realm.setDefaultConfiguration(config)