Background: I want to validate XML-files against a schema automatically. For this I created a maven-project and a XMLValidator
-class in src/main/java
.
To run the tests I created a XMLValidatorTest
in src/test/java
. My idea was to put the XML and XSD files, I want to validate, into the src/test/resources
folder and "grab" them by their filename. But when I run mvn test
the files are not found.
My test-class:
public class XMLValidatorTest {
XMLValidator xmlvalidator;
// XSD is in src\test\resources\XSD\myXSD.xsd
String xsdFileNameWithPath = "XSD\\myXSD.xsd";
@Before
public void setup() {
xmlvalidator = new XMLValidator();
}
@Test
public void testValidate() {
// XML is in src\test\resources\XML\test001.xml
String xmlFileNameWithPath = "XML\\test001.xml";
assertTrue(xmlvalidator.validate(xmlFileNameWithPath, xsdFileNameWithPath));
}
}
When I run mvn test
I get a file not found exception for e.g. java.io.FileNotFoundException: D:\workspace_eclipse\XSDTester\XSD\myXSD.xsd
- which is right as it's in the resource folder.
I tried the solution from Maven (surefire): copy test resources from src/test/java by copying the files via a <testresources>
-tag but it has no effect.
<build>
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
</testResource>
</testResources>
</build>
Any advise?
P.S. In my XMLValidator
I try to use the given files via:
Source xmlFile = new StreamSource(new File(xmlFileNameWithPath));
Source xsdFile = new StreamSource(new File(xsdFileNameWithPath));
edit
I'm again trying to implement Michele Sacchetti advise using a this.getClass().getResourceAsStream()
.
So to retrieve the XML file I try this
validate (String xmlFileNameWithPath, String xsdFileNameWithPath) {
Source xmlFile;
try {
// give systemid according to: https://stackoverflow.com/questions/10997453/java-xml-validation-does-not-work-when-schema-comes-from-classpath
xmlFile = new StreamSource(getClass().getResourceAsStream(xmlFileNameWithPath), getClass().getResource(xsdFileNameWithPath).toString());
} catch (Exception e) {
System.out.println("XML is null");
return false;
}
// ... further steps, trying to get the XSD and validate them
}
and call the function via (as Michele Sacchetti said with omiting src\test\resources
)
// XSD is in src\test\resources\XSD\myXSD.xsd
String xsdFileNameWithPath = "XSD\\myXSD.xsd";
// XML is in src\test\resources\XML\test001.xml
String xmlFileNameWithPath = "XML\\test001.xml";
validate(xmlFileNameWithPath, xsdFileNameWithPath);
But I always get a NPE then trying to get the StreamSource
for the file.