23

I am trying to assert that a given array contains at least one instance of a given element. Is there an assert method that already does this? If so which one?

I am using Java6 and JUnit3.

4 Answers 4

42

You can cast the array to a list:

assertTrue(Arrays.asList(yourArray).contains(yourElement));
Sign up to request clarification or add additional context in comments.

Comments

16
assertThat(Arrays.asList(yourArray), hasItem(yourElement));

This will give you fine-grained information in the event of a test failure. It will print out your element and the collection it's looking in.

3 Comments

This is the best answer. is 'hasItem' new?
@Sungam hasItem() is a part of Java Hamcrest, which was last updated in 2012.
hasItem() is deprecated
14

Not a built-in assert, no. You'd need to use assertTrue() and check the array yourself using something like Arrays.binarySearch(), ArrayUtils.contains(), or your own method.

2 Comments

the thing I would add is the user might want to build their own TestUtil that has a method testArrayContains(ary, object)
I went with the ArrayUtils approach, It seems my Project is including Apache Commons. I was about to create my own method, but I might as well use that one.
1

You can try containsInAnyOrder

assertThat(actual, containsInAnyOrder(expected));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.