package pers.fq.testng; import org.testng.Assert; import org.testng.annotations.*; import java.util.*; /** * Created by fang on 17/5/5. */ public class HelloWordTest { private HelloWord helloWord; // 调用测试用例前初始化变量 @BeforeClass public void beforeClass(){ helloWord = new HelloWord(1); System.out.println("BeforeClass"); } @AfterClass public void afterClass(){ System.out.println("AfterClass"); } @BeforeMethod public void beforeMethod(){ System.out.println("BeforeMethod"); } @AfterMethod public void afterMethod(){ System.out.println("AfterMethod"); } @Test public void testGetValue() throws Exception { Assert.assertEquals(helloWord.getValue(), 1); } @Test public void testGetNull() throws Exception { Assert.assertNull(helloWord.getNull()); } @Test public void testGetTrue() throws Exception { Assert.assertTrue(helloWord.getTrue()); } @Test public void testAssertMap() throws Exception { Map map1 = new HashMap(); map1.put("a","1"); map1.put("b","2"); Map map2 = new LinkedHashMap(); map2.put("b","2"); map2.put("a","1"); Assert.assertEquals(map1, map2); // map支持嵌套 Map map3 = new LinkedHashMap(); map3.put("c","3"); Map map4 = new LinkedHashMap(); map4.put("c","3"); map1.put("x",map3); map2.put("x",map4); Assert.assertEquals(map1, map2); } @Test public void testAssertByteArray() throws Exception { byte [] bytes1 = "abc".getBytes(); byte [] bytes2 = "abc".getBytes(); Assert.assertEquals(bytes1, bytes2); } @Test public void testAssertIterator() throws Exception { // 迭代顺序要保持一致 List list1 = new ArrayList(); list1.add(1); list1.add(2); List list2 = new ArrayList(); list2.add(1); list2.add(2); // 2个Collection 对比 Assert.assertEquals(list1, list2); // 2个Iterator 对比 Assert.assertEquals(list1.iterator(), list2.iterator()); } // 测试抛出异常 @Test(expectedExceptions = NullPointerException.class) public void testGetException() throws Exception { throw new NullPointerException(); } // 测试超时(单位 ms) @Test(timeOut = 300) public void testTimeout() throws Exception { Thread.sleep(200); } // 禁用测试用例 @Test(enabled = false) public void testDisable() throws Exception {} // 测试依赖(testGetTrue 测试通过才执行当前测试) @Test(dependsOnMethods = "testGetTrue") public void testDependsOnMethods() throws Exception { System.out.println("run if [testGetTrue] pass"); Assert.assertTrue(true); } // 定义DataProvider @DataProvider(name = "provideNumbers") public Object[][] provideData() { return new Object[][] { { 10, 20 }, { 100, 110 }, { 200, 210 } }; } // 将DataProvider中的数据,依次传递给测试函数 @Test(dataProvider = "provideNumbers") public void testPlus(int number, int expected) { Assert.assertEquals(number + 10, expected); } }