M
M
Maxim2013-07-12 22:16:01
Java
Maxim, 2013-07-12 22:16:01

Unit test for a method returning a list of objects

There is a service class, it has methods that return a list of objects according to some criterion, for example:

public class PersonService { public List<Person> findAll(){ ... return ...; } ... }

How to correctly (competently) write a unit test for such a method? Namely:
1. How two lists of objects (tested and reference) are compared, in junit, as far as I understand, there is no such box. Moreover, taking into account the sorting of objects, in one case it may be important, in another it is not.
2. How to define and fill in the reference list of objects? Those. Directly hard-code filling the list with statics? Then the code will lose readability. Or store it in a file and load it into a list? How is it accepted?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lavir_the_Whiolet, 2013-07-13
@Lavir_the_Whiolet

1. I would compare element by element. For example, like this (pseudocode):

result := PersonService.findAll(...);
ref := <эталонные объекты>
assert(result.getSize() == ref.getSize());
for (it1 = result.iterator(), it2 = ref.iterator(); it1.hasNext();) {
    assert(it1.next().equals(it2.next()));
}

If the order is not important, then both lists are sorted beforehand.
2. Hard-code filling the list with statics. The “load from file” solution is essentially the same, only the creation of reference objects is written in a different language (the language of the external file format). Do you want to develop a new data format, write a parser for it, integrate it into Junit and describe reference objects on it, or is it still more profitable to describe reference objects in Java?

G
gvsmirnov, 2013-07-13
@gvsmirnov

1. Use hamcrest.org/ , namely IsIterableContainingInOrder
2. The second is better with rigid statics, this is normal for tests.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question