When writing unit tests I need some objects with sample data. For example suppose I have an Order object. One needs to write code like this -
Order o = new Order();
o.setId(3);
o.setAmount(2830.9);
List<Item> items = new ArrayList<Item>();
Item i = new Item();
i.setId(3);
i.setCost(34);
items.add(i);
o.setItems(items);
It is a lot more frustrating and redundant than it looks here because a real object is likely to have lot more attributes and nested objects.
And if one needs multiple orders ...
What is the best way to create mock data objects for testing?
Off the top of my head I'm thinking about deserializing my objects from Json. Is there a standard, efficient way to do this?
Another approach might be to generate random values for the attributes.
A utility like PODAM or openpojo can help.
I'll try to mix the two approaches as appropriate. For example - generate the object with PODAM and then manually set the values that can't be random.
Generally DTO contain only fields and no logic which needs to be mocked out.
I would use a DTO as a mock of itself. If the DTO has logic in it you might like to mock out, I would move the logic out of the DTO.
To create DTO, I would do this from text, either in the test itself, or from an external file. You could use JSon, but if you don't use that already I would use XMLEncoder/XMLDecoder. Its not pretty XML but it is built in so you don't need an extra library.
If you can, you might be able to create DTOs from the logs of the application, so you can recreate a realistic scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With