Tuesday, 12 July 2022

How to test the ordering of collection or list elements in junit?

Sometimes you may want to check whether given collection has elements in the specific order or not. Using IsIterableContainingInOrder class, you can address this use case.

 


CollectionElementsOrderTest.java

package com.sample.app;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Assert;
import org.junit.Test;

public class CollectionElementsOrderTest {
	
	@Test
	public void collectionTest() {
		final List<Integer> actual = Arrays.asList(11, 3,7, 5, 2);
		Collections.sort(actual);
		
		Assert.assertThat(actual , IsIterableContainingInOrder.contains(2, 3, 5, 7, 11));
	}

}

 

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment