I have a set of autotests on junit 5, maven, java. I need to write a script or method that checks if there are failed tests from previous execution. And if there are such tests, then run them.
In my TestWatcher I get a list of fallen tests, but I don't understand how to tell maven to only run them. I know of an option to run tests via mvn test -Dtest="TestClass1, TestClass2", but this is not an option if there are, for example, 20 tests.
The @RepeatedTest junit annotations, as well as the surefire rerunFailingTestsCount property, are not appropriate because they are triggered immediately on a dropped test. Which is good, of course, but not for this specific task.
As far as I understand, there is an option to run specific tests using LauncherFactory. But there is another option, which is not particularly designed for a large number of tests. In summary - I catch the failed tests and write them to the file. Then I go through them and substitute them in the mvn test command. This is what the implementation looks like:
This utility writes each value obtained to a file
public static void writeLine(final String value, final String filepath) throws IOException {
try (FileWriter fileWriter = new FileWriter(filepath, true)) {
fileWriter.append(value);
fileWriter.append("\n");
fileWriter.flush();
}
In the testFailed method of the class that implements TestWatcher I trigger writing the name of the fallen method to a file. FileUtils - the name of the class where the utility is located. Substring is needed to trim () from the method
try {
FileUtils.writeLine(context.getDisplayName().substring(0, context.getDisplayName().length() - 2),
"failedTests"); }
Finally, I have a sh script that reads the file and flips through the name of the methods.And then clears the file
filepath="failedTests.txt"
testclass="*Test#"
script=""
for var in $(cat $filepath)
do
script+="${testclass}${var}, "
done
mvn -Dtest="$script" test
true > "$filepath"
The output will be a string like mvn -Dtest=*Test#failmethod1, *Test#failmethod2, " test. Running the script will only run the tests that fell in the last run.
filepath="failedTests.txt" - file, where the tests were recorded and where to take the dropped tests from.
I have all classes with the nameTest signature. So I use the *Test construct. That is, I select all classes. You can read about template-based class selection here. It also explains why the # symbol is needed (to choose a specific method).
true > "$filepath" - clean the file