Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit 3 - Array contains a given element

Tags:

java

arrays

junit

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.

like image 285
Tiago Veloso Avatar asked Jun 24 '11 15:06

Tiago Veloso


People also ask

How do you check if an array has a certain value?

For primitive values, use the array. includes() method to check if an array contains a value. For objects, use the isEqual() helper function to compare objects and array. some() method to check if the array contains the object.

How do you check if a value is present in a string array?

String Arrays The simplest and easiest way to check if a string array contains a certain value is the following: Convert the array into a list. Use the List. contains() method to check if the value exists in the list.

How do I find a string in an array?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.


2 Answers

You can cast the array to a list:

assertTrue(Arrays.asList(yourArray).contains(yourElement));
like image 109
Kevin Bowersox Avatar answered Sep 21 '22 17:09

Kevin Bowersox


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.

like image 21
bheussler Avatar answered Sep 22 '22 17:09

bheussler