假设我有下面的类,一个简单的类,只是将三个字符串添加到名为 ar 的字符串 ArrayList 中。
public class Testcases {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
public ArrayList<String> myArray() {
ArrayList<String> ar = new ArrayList<String>();
ar.add("Customer1");
ar.add("Customer2");
ar.add("Customer3");
return(ar);
}
}
如何使用 Junit 测试来确保字符串确实进入了 ArrayList?
更新
我的 TestcasesTest 文件 - 测试完成的地方,如下所示:
@Test
public void testMain() {
System.out.println("main");
String[] args = null;
Testcases.main(args);
// TODO review the generated test code and remove the default call to fail.
// fail("the test case is a resul in the prototype");
}
/**
* Test of add method, of class Testcases.
*/
@Test
public void testMyArray() {
assertEquals(Arrays.asList("Customer1", "Customer2", "Customer3"), myArray());
}
}
最佳答案
给你:
public class Testcases {
public List<String> myArray() {
List<String> ar = new ArrayList<>();
ar.add("Customer1");
ar.add("Customer2");
ar.add("Customer3");
return ar;
}
}
class TestcasesTest {
@Test
public void testMyArray() {
Testcases testcases = new Testcases();
assertEquals(Arrays.asList("Customer1", "Customer2", "Customer3"), testcases.myArray());
}
}
我对你的方法做了一些改进:
- 尽可能在返回类型和变量声明中使用接口(interface)类型。所以我将返回类型和局部变量中的
ArrayList
更改为List
- 不需要
return(ar)
中的括号,这样更简单、自然:return ar
关于java - ArrayList 上的 Junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27281306/