英文:
Unit testing an array converted set
问题
我有一个数组。我需要将其转换为集合然后进行单元测试。我成功地将数组转换为集合。但是单元测试不起作用。我是一个新的学习者,特别是在单元测试方面。请帮助。
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()));
}
}
我编写的单元测试案例:
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);
}
}
英文:
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);
}
}
答案1
得分: 2
你无法单元测试一个通过 main
方法公开其 API 的类,除非采用丑陋的黑客方法。如果将 ArrToSet
重构为公开有意义的 API,测试将变得更容易:
public class ArrToSet {
public Set<String> convert(String[] array) {
return Arrays.stream(array).collect(Collectors.toSet());
}
}
现在可以轻松进行测试:
@Test
void test() {
ArrToSet arrToSet = 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));
}
英文:
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));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论