Now We Need a Helper
Now we have a decision to make. How do we test that the customer can be converted to XML? Should Customer have a method like toXML? Or should we have a helper class do the job? The Single Responsibility Principle (SRP) tells us that a class should have one and only one reason to change. If we put XML stuff into the Customer class, then Customer will have two reasons to change:
Any business rules or content having to do with Customer itself
Any changes to the XML schema or XML libraries
So we make the decision to use a helper class instead of a method of Customer.
NOTE
For more on the Single Responsibility Principle, see page 95 of my book Agile Software Development: Principles, Patterns, and Practices (Prentice Hall, 2002, ISBN 0135974445).
We write a new line of code into the test to express our decision:
public void testToXML() throws Exception { Customer c = new Customer(); c.name = "John Smith"; c.address = "55 Somewhere, City, State Zip"; c.email = "jsmith@somewhere.com"; c.phone = "111-222-3333"; c.fax = "444-555-6666"; c.cellPhone = "777-888-9999"; Element e = CustomerXMLConverter.toXML(c); }
This doesn't compile. So we write the simplest code that will make it compile:
public class CustomerXMLConverter { public static Element toXML(Customer c) { return null; } }
The test compiles and runs, so it's time to make it actually test something. We add a clause to the test to check that the name was properly added to the XML:
public void testToXML() throws Exception { Customer c = new Customer(); c.name = "John Smith"; c.address = "55 Somewhere, City, State Zip"; c.email = "jsmith@somewhere.com"; c.phone = "111-222-3333"; c.fax = "444-555-6666"; c.cellPhone = "777-888-9999"; Element e = CustomerXMLConverter.toXML(c); assertEquals("John Smith", e.getChild("name").getTextTrim()); }
This compiles, but fails with a NullPointerException because toXML is returning null. So we have to make toXML actually do something:
public static Element toXML(Customer c) { Element customer = new Element("customer"); return customer; }
Hmm. As I wrote that line of code, I realized that I don't have a test for it. I should add something to the test that makes sure that the name of the customer element is, in fact, customer.
Element e = CustomerXMLConverter.toXML(c); assertEquals("customer", e.getName()); assertEquals("John Smith", e.getChild("name").getTextTrim());
This compiles and fails on the "John Smith" test, so apparently the customer element is properly named. Now let's get whole test to pass.
public static Element toXML(Customer c) { Element customer = new Element("customer"); customer.addContent(new Element("name").setText(c.name)); return customer; }