This is my test so far:
@Test(expected = FileNotFoundException.class)
public void testExpectedException() {
UserDataObject u = new UserDataObject("rob123", "Smith", "Robert", "Danny", 1);
FlatFileStorage ffstorage = new FlatFileStorage();
ffstorage.verifyUser(u, "dsfsdfsfdsdf.txt");
However, the test seems to fail! Even though when I run it, the error message actually gets printed out from the method on the console too, like this
dsfsdfsfdsdf.txt (The system cannot find the file specified)
Am I missing something really obvious here?
EDIT** Here is the method I'm actually testing
public void verifyUser(UserDataObject u, String filename) {
String eachline = "";
String uname = u.getUsername();
Scanner sc;
try {
BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
StringBuilder sb = new StringBuilder();
while ((eachline = br.readLine())!=null)
{
if(eachline.indexOf("Username: " + uname)!=-1)
{
int lineStart = eachline.indexOf("Username: " + uname);
int lineEnd = eachline.indexOf("end" + uname + ";");
int unameLength = uname.length();
String lineStatus = eachline.substring(lineStart, lineEnd + 4 + unameLength);
//System.out.println(lineStatus);
String newLineStatus = lineStatus.replace("VerifyStatus: 0", "VerifyStatus: 1");
sb.append(newLineStatus+"\n");
}else{
sb.append(eachline+"\n");
}
}
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filename)));
PrintWriter out = new PrintWriter(bw);
out.print(sb.toString());
out.flush();
out.close();
} catch (FileNotFoundException e) {
System.out.println("Error: Could not find database/storage.");
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("There has been an error: " + e.getMessage());
e.printStackTrace();
}
}
The issue is that your
verifyUser(UserDataObject u, String filename)
method catches both exceptionsFileNotFoundException
andIOException
and hence it is not propagated to your test method.Your test is failing because you are expecting the FileNotFoundException, but it not actualy thrown from a method. Why? Because of try/catch wrapper, that swallows the exception, only printing the stack trace to the output.
Change the catch block to
and test will pass