Java JUnit4:使用ArrayList类型测试读取文件方法
我已经编写了一个测试来检查我读取.txt文件的java方法是否能够成功执行Java JUnit4:使用ArrayList类型测试读取文件方法,java,testing,junit4,file-management,Java,Testing,Junit4,File Management,我已经编写了一个测试来检查我读取.txt文件的java方法是否能够成功执行 @Test public void testRead() { String filePath = "testpackread.txt"; ArrayList<Card> testReaderMethod = FileManager.readFile(filePath); assertEquals(4,testReaderMethod
@Test
public void testRead() {
String filePath = "testpackread.txt";
ArrayList<Card> testReaderMethod = FileManager.readFile(filePath);
assertEquals(4,testReaderMethod);
}
@测试
公共void testRead(){
字符串filePath=“testpackread.txt”;
ArrayList testReaderMethod=FileManager.readFile(文件路径);
assertEquals(4,testreader方法);
}
我打开的文件包含数字4,如果它将第一行读取为4,我只想通过测试
测试运行并且方法成功,所以问题不在于我如何编写方法。
命令行中的输出显示:
java.lang.AssertionError: expected:<4> but was:<[project.Card@3043fe0e]>
java.lang.AssertionError:应为:但为:
如果有帮助,这是正在测试的方法:
public static ArrayList<Card> readFile(String packPath){
ArrayList<Card> cardDeck = new ArrayList<>();
int cardNumber;
BufferedReader in = new BufferedReader(new FileReader (packPath));
String line = in.readLine();
while(line!= null){
cardNumber = Integer.parseInt(line);
if (cardNumber > 0) {
cardDeck.add(new Card(cardNumber));
line = in.readLine();
}else {//If found invalid card stop immediately and clear cardDeck
System.out.println("[Message] : Integer must be positive");
cardDeck.clear();
line = null;
}
in.close();//Close file reader
return cardDeck;
}
publicstaticarraylistreadfile(stringpackpath){
ArrayList cardDeck=新的ArrayList();
int卡号;
BufferedReader in=新的BufferedReader(新文件读取器(packPath));
String line=in.readLine();
while(行!=null){
cardNumber=Integer.parseInt(行);
如果(卡号>0){
添加(新卡(卡号));
line=in.readLine();
}否则{//如果发现无效卡,立即停止并清除cardDeck
System.out.println(“[消息]:整数必须为正”);
cardDeck.clear();
行=空;
}
in.close();//关闭文件读取器
返回卡片组;
}
非常感谢您提供的任何帮助,我希望我已经清楚了您的断言相当于:
if (Integer.valueOf(4).equals(Arrays.asList(new Card(4))))
如果你尝试一下,它也不起作用,对吗
也许(如果卡
实现等于
):
或
在
assertEquals()
中,您正在比较两种不同的类型:一个整数和一个类型为Card
的数组列表。但是如何解决这个问题?getCardNumber()应该是什么?您没有提供太多信息,但您的示例显示了新卡(cardNumber)
,因此我假设它将cardname
存储在一个字段中,因此getcardname
是我假设存在的某个名称对应的getter。
assertEquals(Arrays.asList(new Card(4)), testReaderMethod);
assertEquals(1, testReaderMethod.size());
assertEquals(4, testReaderMethod.get(0).getCardNumber());