Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit - assert the list contains

I'm creating a List (ArrayList) that contains few elements. I want to make sure it contains the elements I added. now, this works only some of the times, since the order changes:

@Test
public void testThreeReporters(){
    ClientConfig myConfig = new ClientConfigFactory().getConfig().withMetricsReporters(new HashSet<>(Arrays.asList(ClientConfig.MetricsReporterType.LOG, ClientConfig.MetricsReporterType.GRAPHITE, ClientConfig.MetricsReporterType.CLOUD_WATCH)));
    List<ScheduledReporter> reporters = MetricsFactory.configureMetricsReporters(MetricsFactory.createMetricsClient(),myConfig);
    assertEquals(3, reporters.size());

    assertTrue(reporters.get(2) instanceof Slf4jReporter);
    assertTrue(reporters.get(1) instanceof GraphiteReporter);
    assertTrue(reporters.get(0) instanceof CloudWatchReporter);
}

I want to use 'contains' in order to not be depend on the order. I tried something like:

 assertTrue(Arrays.asList(reporters).contains((Arrays.asList(ClientConfig.MetricsReporterType.LOG, ClientConfig.MetricsReporterType.GRAPHITE, ClientConfig.MetricsReporterType.CLOUD_WATCH))));

and some other combinations, but it doesn't work.

like image 779
user2880391 Avatar asked Mar 12 '17 08:03

user2880391


Video Answer


2 Answers

assertEquals(3, reporters.size());
assertTrue(reporters.stream().anyMatch(e -> e instanceof Slf4jReporter));
assertTrue(reporters.stream().anyMatch(e -> e instanceof GraphiteReporter));
assertTrue(reporters.stream().anyMatch(e -> e instanceof CloudWatchReporter));
like image 81
JB Nizet Avatar answered Nov 15 '22 22:11

JB Nizet


There isn't really an easy way to do this with plain JUnit out of the box. You could develop a helper method to make this easy using the technique demonstrated by @JBNizet in his answer.

Or you could use an additional testing library that can help with this. For example using AssertJ you could do this:

import static org.assertj.core.api.Assertions.assertThat;

// ...

assertThat(reporters).extracting("class").contains(
    Slf4jReporter.class,
    GraphiteReporter.class,
    CloudWatchReporter.class
);

If you use Maven, you can add assertj dependency like this:

<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.4.1</version>
</dependency>
like image 40
janos Avatar answered Nov 15 '22 23:11

janos