Caiz22
Caiz22

Reputation: 817

JUnit Test that ArrayList elements aren't duplicates

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;
} 

Upvotes: 7

Views: 6375

Answers (5)

Fede Garcia
Fede Garcia

Reputation: 807

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();
}

Upvotes: 10

davidxxx
davidxxx

Reputation: 131526

In fact you have to assert more than that.
To check the actual behavior of the method, you should indeed assert from the returned list that :

  • the list has the expected size

Assert.assertEquals(size, list.size());

  • the list doesn't contain dup

Assert.assertEquals(new HashSet<Long>(list).size(), actualList.size());

  • the list elements are in the range min-max passed to.

for (long v : list){ Assert.assertTrue(v " + " is not in the expected range", v >= min && v <= max); }

As M. le Rutte underlined, I would also argue that the method API would make more sense to return a Set instead of List as an order of elements is not expected : the number are random.

And as a side note, your implementation is not efficient.
With a large range and a size requested close to the range size, you could loop much more than required.

Upvotes: 6

Dishonered
Dishonered

Reputation: 8851

You can do this to check if there are no duplicates,

assertEquals(number.size(),number.stream().distinct().collect(Collectors.toList()).size());

where number is your arrayList. Use this

import static junit.framework.Assert.assertEquals

Upvotes: 0

zlakad
zlakad

Reputation: 1384

Another approach can be to fill your ArrayList with Integers from min to max, and then call Collections.shuffle(aList).

Upvotes: 0

Liviu Florin Ilie
Liviu Florin Ilie

Reputation: 97

You can put your elements into an Set and then compare sizes.

assert new HashSet(list).size() == list.size()

Upvotes: 0

Related Questions