Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to mock DTOs in Java?

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?

like image 655
Kshitiz Sharma Avatar asked Sep 17 '12 07:09

Kshitiz Sharma


2 Answers

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.

like image 92
Kshitiz Sharma Avatar answered Nov 15 '22 16:11

Kshitiz Sharma


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.

like image 23
Peter Lawrey Avatar answered Nov 15 '22 17:11

Peter Lawrey