Java Reference
In-Depth Information
Verifying the mapping document
JDO and Hibernate define the O/R mapping using an XML document. We can
write tests that verify that the mapping document correctly specifies the mapping
from classes, fields, and relationships to tables, columns, and foreign keys. For
example, it is quite easy to write a test that verifies that a class is mapped to a par-
ticular table and that all of its fields are mapped to columns of that table. This
kind of test is extremely useful since it fails whenever you forget to map a newly
defined field. With a little bit more effort we could also write a test that verifies
that each field is mapped to the correct column.
One straightforward way to implement this kind of test is to use XmlUnit
[XmlUnit], which is a JU nit extension for testing XML documents. A test for the
ORM can use XmlUnit to make assertions about the contents of the document.
For example, a test can verify that the PendingOrder class is mapped to the
PENDING_ORDER table using the following code:
class PendingOrderMappingTests extends XMLTestCase {
public void testMapping() throws Exception {
Document mappingDocument = …;
assertXpathEvaluatesTo("PENDING_ORDER",
"hibernate-mapping/class[@name='PendingOrder']/@table",
mappingDocument);
}
}
The test case extends XMLTestCase , which is provided by XmlUnit. It calls
assertXpathEvaluatesTo() , which is an XmlUnit method that throws an excep-
tion if the specified XPath expression does not evaluate to the expected value.
The XP ath expression used by this particular test retrieves the value of the table
attribute of a <class> element that is a child of <hibernate-mapping> and has a
name attribute whose value is PendingOrder . The test could also call to assertX-
pathEvaluatesTo() to verify that each field is mapped to the correct column. It is
also valuable to use reflection to get the names of all of the fields and verify that
each field is mapped.
You can use XmlUnit to test the O/R mapping for a variety of ORM frame-
works. The one drawback is that writing the XP ath expressions can be tricky. A
better option, which can be used with some ORM frameworks, is to get the O/R
mapping metadata from the ORM framework. Some ORM frameworks provide an
API, which returns Java objects that describe the mapping. An ORM test can then
make assertions about the objects. This approach does not require detailed
 
 
 
 
 
 
Search WWH ::




Custom Search