This is the function that I’ve written:
private String getPatternFromLogFile() {
final File dir = new File(".");
try {
String fileContents = readFile(dir.getCanonicalPath()
+ "\\sshxcute.log");
Pattern patternDefinition = Pattern.compile(
".*Start to run command(.*)Connection channel closed",
Pattern.DOTALL);
Matcher inputPattern = patternDefinition.matcher(fileContents);
if (inputPattern.find()) {
return inputPattern.group(1);
}
} catch (IOException e) {
LOGGER.log(Level.DEBUG, e.getMessage());
}
return "";
}
I’m trying to get the contents of the file “sshxcute.log”.
readFile() is a function in this class itself.
I want to write a test case which goes inside the if block and returns whatever I want so that I can assert it.
Is this the right approach?
Could someone please help me to write JUnit for this.
I’m new to JUnit and any help would be great.
Thank you.
Your method is doing a couple of things, and that makes it difficult to reliably unit test. It’s reading a file, and then applying the regexp(s).
I would perhaps split this up. Create a class that reads the file and creates an array of lines, a stream etc. Then create a component that reads this array, stream etc. In that class perform your regexp work.
That way you can test your regexp component easily against canned data and not rely on the contents of files (I note your path above is hard-coded – that makes life more difficult). Becuase you’ve split the regexp component from the file reading component you can easily capture its output (for many different scenarios – not just the one provided by your one example file)