Switch
Switch

Reputation: 15463

Junit | comparing dynamic objects

How do I compare dynamic object types in Junit for example:-

while (objList.hasNext()) {
      Object<String> obj = objList.next();
      Assert.assertEquals("expected", obj); 
}

In this scenario if one occurrence is failed the whole test will fail. Is it a good approach if I use a condition before the assert test to pin point the expected String

like this:

while (objList.hasNext()) {
      Object<String> obj = objList.next();
      if (obj.equals("expected")) {
           Assert.assertEquals("expected", obj); 
      }
}

but in this case there's no point of having a Junit assert test. Because I'm already doing what Junit is intended to do Thanks.

Upvotes: 0

Views: 1381

Answers (4)

Clive Evans
Clive Evans

Reputation: 658

It's not entirely clear what you're asking here. It'd be easier if we knew what you were iterating over, but assuming that it's an Iterable, you're probably best off looking at the hamcrest matchers.

For example

asserThat(objList, Matchers.hasItem(expected);

will pass if expected is equal to an element in your iterable. Check out the matchers bundled with junit, or add the external hamcrest libraries to your test project.

Upvotes: 1

jens
jens

Reputation: 1872

You might use array based assertions. For this purpose you would have to convert your enumeration to an array.

Object[] enumAsArray = Collections.list(objList).toArray();

Upvotes: 0

oers
oers

Reputation: 18714

Have a look at the ErrorCollector Rule.

It allows you to "collect" errors and output them in the end. JUnit will not fail at the first error if you use this.

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533930

What I do for larger data structures is to use a sensible toString() method and compare this.

e.g.

assertEquals(""+expected, ""+obj);
assertEquals(expected, obj);

The reason for doing this is that with an IDE (to show you the difference) or text comparison you can see all the values which are different and how they differ. The second check is to confirm they really are equal.

Upvotes: 0

Related Questions