TestNG 支持很多断言。它有org.testng.Assert类,它扩展了 Java 对象类java.lang.object。
为了具体比较两个列表,TestNG 的 Assert 类有一个称为 的方法,assertEquals(Object actual, Object expected)并且该方法有一个扩展版本,其中自定义消息为assertEquals(Object actual, Object expected, String message).
如果 - 此方法返回 True -
两个对象都是列表,
两个列表的大小相同,并且
如果列表的元素顺序相同。
如果这些条件中的任何一个不为 True,它将返回 False。
在本文中,我们将讨论如何在 TestNG 中比较两个列表。
解决此问题的方法/算法 -
第 1 步- 创建一个 TestNG 类“ NewTestngClass ”。
第 2 步- 在类中编写三个不同的 @Test 方法,如编程代码部分所示。
1 st @Test Method - 它有 2 个完全相同的列表;满足所有 3 个条件并比较这 2 个列表。该测试将通过。
2 nd @Test Method - 2 个列表的大小不同,此测试将引发异常。
3 rd @Test Method - 列表中元素的顺序不一样,这个测试也会抛出异常。
第 3 步- 现在创建testNG.xml如下所示以运行 TestNG 类。
第 4 步-testNG.xml直接在 IDE 中运行或运行 testNG 类,或使用命令行编译并运行它。
示例
对常见的 TestNG 类“ NewTestngClass ”使用以下代码-
src/NewTestngClass.java
import org.testng.Assert; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; public class NewTestngClass { @Test public void testCase1() { System.out.println("in test case 1 of NewTestngClass"); List<String> expectedName = new ArrayList<String>(); expectedName.add("ramesh"); expectedName.add("mahesh"); expectedName.add("suresh"); List<String> actualName = new ArrayList<String>(); actualName.add("ramesh"); actualName.add("mahesh"); actualName.add("suresh"); Assert.assertEquals(actualName,expectedName, "Comaparsion of 2 lists"); } @Test public void testCase2() { System.out.println("in test case 2 of NewTestngClass"); List<String> expectedName = new ArrayList<String>(); expectedName.add("ramesh"); expectedName.add("mahesh"); expectedName.add("suresh"); List<String> actualName = new ArrayList<String>(); actualName.add("ramesh"); actualName.add("mahesh"); Assert.assertEquals(actualName,expectedName,"Comparison of 2 lists"); } @Test public void testCase3() { System.out.println("in test case 3 of NewTestngClass"); List<String> expectedName = new ArrayList<String>(); expectedName.add("ramesh"); expectedName.add("mahesh"); expectedName.add("suresh"); List<String> actualName = new ArrayList<String>(); actualName.add("suresh"); actualName.add("ramesh"); actualName.add("mahesh"); Assert.assertEquals(actualName,expectedName,"Comaparsion of 2 lists"); } }
测试NG.xml
这是一个配置文件,用于组织和运行 TestNG 测试用例。当需要执行有限的测试而不是完整的套件时,它非常方便。
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Suite1"> <test name = "test1"> <classes> <class name = "NewTestngClass"/> </classes> </test> </suite>输出结果
in test case 1 of NewTestngClass in test case 2 of NewTestngClass java.lang.AssertionError: Comaparsion of 2 lists: lists don't have the same size expected [3] but found [2] Expected :3 Actual :2 in test case 3 of NewTestngClass java.lang.AssertionError: Comaparsion of 2 lists: Lists differ at element [0]: ramesh != suresh expected [ramesh] but found [suresh] Expected :ramesh Actual :suresh =============================================== Suite1 Total tests run: 3, Passes: 1, Failures: 2, Skips: 0 ===============================================