I am using JUnit 4 parametrized test annotations to perform equality tests on data coming from a unknown number of files.
For some weird reason, the test always checks the same file, as if the same Array was always used from the Collection used to pass the parameters.
I’m sure I’m missing something elementary here, but I can’t see what. Could someone provide me with a helpful tip ?
Here is my code :
@RunWith(value = Parameterized.class)
public class XMLUnitTest extends XMLTestCase {
static final File ORACLE_DIR = new File("some/directory/path");
static final String PATH_TO_LOG = "some/file/path";
private String oracleXml;
private String testXml;
private String testName;
public XMLUnitTest(String o, String t, String n) {
this.oracleXml = o;
this.testXml = t;
this.testName = n;
}
// (snip) file-handling methods
@Parameters
static public Collection<Object[]> data() {
String logfile = null;
File[] xmlFilesArray;
ArrayList<String> parsedXMLs = new ArrayList<String>();
ArrayList<String> xmlNames = new ArrayList<String>();
String[] xmlArgs = new String[3];
Collection<Object[]> data = new ArrayList<Object[]>();
try {logfile = readFileAsString(PATH_TO_LOG);}
catch (IOException e) {// (snip) error handling}
String[] parsedLogs = logfile.split("someRegex", 0);
for (int i = 0; i < parsedLogs.length; i++) {
parsedLogs[i] = "<xml>"+parsedLogs[i]+"</xml>";
}
xmlFilesArray = ORACLE_DIR.listFiles();
Arrays.sort(xmlFilesArray, nameCompare);
for (int i = 0; i < xmlFilesArray.length; i++) {
if (!xmlFilesArray[i].isDirectory()) {
try {
parsedXMLs.add(convertXMLFileToString(xmlFilesArray[i].getAbsolutePath()));
xmlNames.add(xmlFilesArray[i].getName());
}
catch (Exception e) {// (snip) error handling}
}
}
for (int i = 0; i < parsedLogs.length; i++) {
xmlArgs[0] = parsedXMLs.get(i);
xmlArgs[1] = parsedLogs[i];
xmlArgs[2] = xmlNames.get(i);
System.out.println(xmlArgs[2]); //debug
data.add(xmlArgs);
}
return data;
}
@SuppressWarnings("unchecked")
@Test
public void equality() throws Exception {
System.out.println("Working on test: "+testName);
// (snip) some testing
}
}
It’s partially obfuscated but there should be everything needed to find my error…
The System.out.prints are used for debug : the one in the static parameter-generator show the names of the correct files, meaning that the object “data” is correct. The one in the test itself always prints the same thing, meaning that the test is always run with the same array of parameters (But it runs 7 times, the number of arrays I have in my collection !) I don’t get it. Is there something I have missed about the type of the parameters to pass to JUnit ?
This
String[] xmlArgs = new String[3];should be in the for-loop.
Your are always updating the same instance of the xmlArgs-Array and inserting it..