Stack Overflow Asked by u.mang on November 10, 2021
I have an array. I am required to convert it into set and then unit test. I successfully did the array to set conversation. But the unit test is not working. I am a new learner specially in unit testing. Please help.
public class ArrToSet {
public static void main(String[] args) {
String[] array = {"a","b","c"};
System.out.println("Original Array: " + Arrays.toString(array));
System.out.println("Array converted to Set: " + Arrays.stream(array).collect(Collectors.toSet()));
}
}
The unit test case I have written:
class ArrToSetTest {
@Test
void test() {
ArrToSet ar = new ArrToSet();
Set<String> set = new HashSet<>();
set.add("a");
set.add("b");
set.add("c");
String actual[] = {"a","b","c"};
assertEquals(set,actual);
}
}
You won't able to unit test a class that exposes its API through a main
method without ugly hacks. If you refactor ArrToSet
to expose meaningful API it'll be much easier to test:
public class ArrToSet {
public Set<String> convert(String[] array) {
return Arrays.stream(array).collect(Collectors.toSet()));
}
public static void main(String[] args) {
String[] array = {"a","b","c"};
System.out.println("Original Array: " + Arrays.toString(array));
ArrToSet arrToSet = ArrToSet();
System.out.println("Array converted to Set: " + arrToSet.convert(array));
}
}
Testing this is easy now:
@Test
void test() {
ArrToSet ar = new ArrToSet();
Set<String> set = new HashSet<>();
set.add("a");
set.add("b");
set.add("c");
String actual[] = {"a","b","c"};
assertEquals(set, arrToSet.convert(actual));
}
Answered by Egor on November 10, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP