【发布时间】:2016-11-17 17:45:26
【问题描述】:
我正在使用 JUnit Test 进行测试,但我遇到了 AssertionFailedError 问题。 我正在使用命令行参数将测试用例传递给主类。
下面是我的 Main.java 代码
public class Main {
public static void main(String[] args) throws IOException {
//Storing all the commands, words, files
ArrayList<String> commands = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
ArrayList<String> files = new ArrayList<>();
for(String arg: args){
if(arg.contains("."))
files.add(arg);
else if(arg.contains("-") && !arg.contains("--"))
commands.add(arg);
else{
if(!arg.contains("--"))
words.add(arg);
}
}
for(String file : files ){
File originalFile = new File(file);
//CHECK IF textFile exists
if(originalFile.exists()){
if(words.size() == 2){
String from = words.get(0), to=words.get(1);
BufferedWriter bw;
//If file exists then check command
for(String command : commands){
if(command.trim().contains("-f")){
File temp = new File("Temp.txt");
temp.createNewFile();
//If Temp.exists
if(temp.exists()){
bw = new BufferedWriter(new FileWriter(temp));
//Fetch all the lines from Orginal File
List<String> lines = Files.readAllLines(Paths.get(originalFile.getName()));
//Add to treemap
TreeMap<Integer,String> tm = new TreeMap<>();
for(int i=0;i<lines.size();i++){
tm.put(i,lines.get(i));
}
//To check first occurence of word in hashmap
for(int i=0;i<tm.size();i++){
String lastLine = tm.get(i);
tm.remove(i);
tm.put(i,lastLine.replaceFirst(from,to));
if(!lastLine.equals(tm.get(i)))
break;
}
//Write treemap to the text file
for(String line: tm.values())
bw.write(line.trim() + "\n");
System.out.println("First Occurence " + originalFile.getName()+ " changed");
bw.close();
originalFile.delete();
temp.renameTo(originalFile);
}else
System.out.println("Error in creating Temp.txt file");
}
}
}
一切正常,文件已创建。我认为代码中没有错误。下面是 MainTest.java
public class MainTest {
// Some utilities
private File createInputFile1() throws Exception {
File file1 = new File("Test.txt");
try (FileWriter fileWriter = new FileWriter(file1)) {
fileWriter.write("Dog is an animal");
}
return file1;
}
private String getFileContent(String filename) {
String content = null;
try {
content = new String(Files.readAllBytes(Paths.get(filename)));
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
// Actual test cases
@Test
public void mainTest2() throws Exception {
File inputFile1 = createInputFile1();
String args[] = {"-f", "Dog", "Cat", "--", "Test.txt"};
Main.main(args);
String expected1 = "Cat is an animal".trim();
String actual1 = getFileContent("Test.txt");
assertEquals("The files differ!", expected1, actual1);
assertTrue(Files.exists(Paths.get(inputFile1.getPath() + ".bck")));
}
}
一切正常,文件 Test.txt 已创建,其中包含文本。 但是我遇到了 AssertionFailedError: 文件不同的错误!预期:Cat is an animal[] 但原为:Cat is an animal[]
为什么 [] 和 [ ] 不同?
【问题讨论】:
-
你为什么要修剪不需要修剪的
String文字String expected1 = "Cat is an animal".trim();。你的意思是修剪文件的内容吗? -
文件的编码是什么?它可能有一个字节编码标记,你的断言会抛出......
标签: java junit error-handling assertions