Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit Test that ArrayList elements aren't duplicates

Tags:

java

junit

Using this method that generates an ArrayList using random values from a called method getRandomInt. What would I assert to create a test method that tests that the ArrayList doesn't contain duplicates?

public static int getRandom(int min, int max) {

    return random.nextInt((max - min) + 1) + min;
}

public static ArrayList<Integer> getRandomIntegers(int size, int min, int max) {

    ArrayList<Integer> number = new ArrayList<Integer>();

    while (number.size() < size) {
        int random = getRandom(min, max);

        if(!number.contains(random)) {
            number.add(random);
        }
    }

    return number;
} 
like image 839
Caiz22 Avatar asked Jul 17 '26 09:07

Caiz22


1 Answers

Using assertJ this is straight forward common-assertions-for-java-collections-in-assertj

@Test
public void noDuplicatesTest(){
    List<Integer> numbers = Lists.newArrayList(1, 52, 12, 39, 45, 98, 100, 565, 6, 13);
    assertThat(numbers).doesNotHaveDuplicates();
}
like image 193
Fede Garcia Avatar answered Jul 18 '26 22:07

Fede Garcia