I am currently writing a JUnit Unit Test Case for a simple method. Here is the method in question:
public static Integer[] findUnpairedNumbers(Integer[] numbers) {
// catches if passed array is empty or uninitialized
if (numbers == null) {
throw new IllegalArgumentException();
}
// HashSet initialized to store unpaired numbers
HashSet<Integer> result = new HashSet<Integer>();
// Loop through numbers array
for (int next: numbers) {
// if HashSet already contains next element, remove that element from the HashSet
if (result.contains(next)) {
result.remove(next);
}
// Otherwise, add it to the HashSet
else {
result.add(next);
}
}
// return the HashSet of unpaired numbers, converting to back to Integer array
return result.toArray(new Integer[result.size()]);
}
Here is the JUnit test I have written:
package program;
import static org.junit.Assert.*;
import org.junit.Test;
public class FindUnpairedTest {
@Test
public void test() {
Integer[] numbers = {1, 2, 4, 5, 7, 7, 8, 8, 9, 1, 5};
Integer[] unpairedCheck = {2, 4};
Integer[] unpaired = findUnpairedNumbers(numbers);
if (unpaired != unpairedCheck) {
fail();
}
}
}
However, the findUnpairedNumbers
class is not recognized by the test class. It is in the same package. Do I need to import anything else? Where am I going wrong here?
Also please let me know if any syntax is unorthodox or if there are other ways I can improve my test case.
findUnpairedNumbers
is a method, not a class... you do have this method in a class, right? If it's not in the same package as the test class you will need to reference it using the full class name as well.