Som
Som

Reputation: 1610

How to call assertEquals for each element in an array stream

I have an array of custom objects. I want to loop through each element and check a particular field of that custom object which is of type String. I want to use assertEquals to compare that value with an expected value. But I am not able to correcty write the statement.

My code :

MyCustomObject[] items = buildItems();
Arrays.asList(items).stream().map(MyCustomObject::getGroupName).forEach(assertEquals("",groupName));

Upvotes: 0

Views: 1284

Answers (3)

M. Justin
M. Justin

Reputation: 21123

You are missing the parameter in the lambda; the groupName value you reference is not declared.

It should be:

.forEach(groupName -> assertEquals("",groupName))

instead of:

.forEach(assertEquals("",groupName))

Making this change results in each element of the list being compared against "" using assertEquals, as desired.

Of note: the compilation error I get when compiling your code calls out that this is the issue:

/Users/You/Path/To/YourTest.java:17: error: cannot find symbol
Arrays.asList(items).stream().map(MyCustomObject::getGroupName).forEach(assertEquals("",groupName));
                                                                                        ^
  symbol:   variable groupName
  location: class YourTest
1 error

Upvotes: 0

lazylead
lazylead

Reputation: 1979

That's a bad idea to iterate through the values and check them on each iteration. For example, what if test failed on 23 iteration of 100 in total (23/100)? You'll need to re-run the tests again once fix for 23 iteration is done...

Its better to use parameterized tests:

You may have several data provides like other methods or CSV format.

Upvotes: -1

ferrouskid
ferrouskid

Reputation: 661

You aren't collecting anywhere yet. You could do this:

List<String> groups = Arrays.asList(items).stream().map(MyCustomObject::getGroupName).collect(Collectors.toList());
groups.forEach(group -> assertEquals(group,groupName));

The first line gets the list of strings that are returned with MyCustomObject::getGroupName and the second line applies a Consumer for each of those strings.

You could also reduce it to a single line, but I think its not always the best to do so because its difficult to read and becomes less interpretable to others :D

Upvotes: 1

Related Questions