測試中斷言的重要性
一、斷言的作用:
1.斷言也就是檢查點,重在判斷我們通過頁面得出來的值與期望值是否相等,如果相等,則代表斷言成功,程序會繼續往下執行,如果不相等,則代表斷言失敗,程序就會在斷言失敗處中止。
示例:
二、斷言的API:
1.Assert.assertEquals
2.Assert.assertFalse(condition)
3.Assert.assertNotEquals(actual1, actual2)
4.Assert.assertNotNull(object)
5.Assert.assertNotSame(actual, expected, message)
6.Assert.assertNull(object, message)
7.Assert.assertSame(actual, expected)
8.Assert.assertTrue(condition)
三、封裝斷言類
斷言結果對程序的影響
1.場景:假如對一個表格里的數據做一個循環比較,如果一斷言失敗就退出,那我們就無法一下子找出全部不符合要求的數據了,那么我們可不可以在斷言時,如果斷言失敗則不退出,等到把整個循環做完后,再整體判斷是否有斷言失敗的地方?
示例:
腳本格式
具體代碼
Assertion.java代碼:
package com.selenium.utils; import org.testng.Assert; public class Assertion { public static boolean flag = true; public static void verifyEquals(Object actual, Object expected) { try { Assert.assertEquals(expected, actual); } catch (Error e) { flag = false; Log.logError("數據對比錯誤-> 期望值為:" + expected + "實際值為:" + actual); } } public static void verifyEquals(Object actual, Object expected, String message) { try { Assert.assertEquals(expected, actual, message); } catch (Error e) { flag = false; Log.logError("數據對比錯誤-> 期望值為:" + expected + "實際值為:" + actual); } } }
在代碼中使用如下:
package com.selenium.test; import org.junit.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.selenium.utils.Assertion; public class testAssertion { // @Test(dataProvider = "number") public void testAssertAndLog4j(String text) { String expected = "b"; String actual = text; Assertion.flag = true; for (int i = 0; i < 3; i++) { System.out.println("斷言開始:" + i); Assertion.verifyEquals(actual, expected, "---測試兩個字符串是否相同"); System.out.println("斷言結束:" + i); } Assert.assertTrue(Assertion.flag); } @DataProvider public Object[][] number() { return new Object[][] { { "a" }, { "b" }, { "c" } }; } }
最后打個廣告,不要介意哦~
最近我在Dataguru學了《軟件自動化測試Selenium2》網絡課程,挺不錯的,你可以來看看!要是想報名,可以用我的優惠碼 G863,立減你50%的固定學費!
鏈接:http://www.dataguru.cn/invite.php?invitecode=G863