This commit related to BAEL-7103 (#15160)

This commit aims to add a test class named "ConvertingHashSetToArrayUnitTest" that provides test methods to convert HashSet to an array.
This commit is contained in:
MohamedHelmyKassab 2023-11-09 00:08:33 +02:00 committed by GitHub
parent e394311aa9
commit 7e81d666c9
1 changed files with 51 additions and 0 deletions

View File

@ -0,0 +1,51 @@
package com.baeldung.toarraymethod;
import org.junit.Test;
import java.util.HashSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConvertingHashSetToArrayUnitTest {
@Test
public void givenStringHashSet_whenConvertedToArray_thenArrayContainsStringElements() {
HashSet<String> stringSet = new HashSet<>();
stringSet.add("Apple");
stringSet.add("Banana");
stringSet.add("Cherry");
// Convert the HashSet of Strings to an array of Strings
String[] stringArray = stringSet.toArray(new String[0]);
// Test that the array is of the correct length
assertEquals(3, stringArray.length);
for (String str : stringArray) {
assertTrue(stringSet.contains(str));
}
}
@Test
public void givenIntegerHashSet_whenConvertedToArray_thenArrayContainsIntegerElements() {
HashSet<Integer> integerSet = new HashSet<>();
integerSet.add(5);
integerSet.add(10);
integerSet.add(15);
// Convert the HashSet of Integers to an array of Integers
Integer[] integerArray = integerSet.toArray(new Integer[0]);
// Test that the array is of the correct length
assertEquals(3, integerArray.length);
for (Integer num : integerArray) {
assertTrue(integerSet.contains(num));
}
assertTrue(integerSet.contains(5));
assertTrue(integerSet.contains(10));
assertTrue(integerSet.contains(15));
}
}