views:

260

answers:

1

Hi!
   In my project we created stub files for testing junits in java(factories) itself. However, we have to externalize these stubs. After seeing a number of serializers/deserializers, we settled on using XStream to serialize and deserialize these stub objects. XStream works like a charm. Its pretty good at what it claims to be. Previously, we had a single factory class say AFactory which produced all the stubs needed for testing different test cases. Now when externalizing each of the stub generated, we hit a road block. We had to create 1 xml file for each stub produced by the factory.
For example,

public final class AFactory{
     public static A createStub1(){ /*Code here */}
     public static A createStub2(){ /*Code here */}  
     public static A createStub3(){ /*Code here */}
}

Now, when trying to move this stubs to external files, we had to create 1 xml file for each stub created(A-stub1.xml, A-stub2.xml and A-stub3.xml). The problem with this approach is that, it leads to proliferation of xml stub files.

I was thinking, how about keeping all the stubs related to a single bean class in a single xml file.

<?xml version="1.0"?>
<stubs class="A">
    <stub id="stub1">
      <!-- Here comes the externalized xml stub representation -->
    </stub>
    <stub id="stub2">
    </stub>
</stubs>

Is there a framework which allows you keep all the stub in xml representation in a single xml file as above ? Or What do you guys suggest should be the right approach to adhere to ?

+1  A: 

I'm not really sure why you are trying to externalize objects this way. Are you trying to maintain a set of "test objects" that you can edit by hand? Not knowing more about what you are actually trying to accomplish, I'd suggest that it would be better to implement this as setUp/tearDown code in your test classes. Using a library like JMock will make this much much easier.

That said, if you truly want to keep these objects as serialized XML files, you can do it simply by creating a "container" class that holds an array/collection of your individual objects. When the container object is serialized, the contained stubs will be stored along with it.

public class StubContainer implements Serializable {
   private ArrayList<Serializable> stubs = new ArrayList<Serializable>();

   public ArrayList<Serializable> getStubs() { 
     return stubs;
   }

   public void setStubs(ArrayList<Serializable> stubs) {
     this.stubs = stubs; 
   }
}

Incidentally, if your needs are simple, you can try using XMLEncoder/XMLDecoder, which come built into the JRE. They are very simple to use, as long as you aren't too picky about the details of the XML format.

Caffeine Coma