數據驅動是作自動化測試中很重要的一部分,數據源的方案也是百花八門了,好比利用外部文件,直接在@DataProvider中寫死等等,咱們今天介紹一下利用enum來作數據源,先來看一下enum的寫法:
ide
public enum TestEnum { OK(200,"success"), FAIL(300,"fail"); private int retCode; private String msg; private TestEnum(int retCode, String msg) { this.retCode = retCode; this.msg = msg; } public int getRetCode() { return retCode; } public void setRetCode(int retCode) { this.retCode = retCode; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Override public String toString() { return retCode+" "+msg; } public static void main(String[] args) { TestEnum[] vs = TestEnum.values(); System.out.println(vs[0].getMsg()); System.out.println(TestEnum.OK.getRetCode()); System.out.println(TestEnum.OK.getMsg()); System.out.println(TestEnum.valueOf("OK").getMsg()); } }
上述代碼複製後,可直接運行!
上述代碼可理解爲有兩組數據,每一組裏面有兩個數據,一個是retCode,一個是msg。如今把enum給加載到@DataProvider中去:測試
public class TestDataDemo { @DataProvider public Object[][] dataProvider(){ TestEnum[] vs = TestEnum.values(); Object[][] obj = new Object[vs.length][]; for (int i = 0; i < vs.length; i++) { obj[i] = new Object[]{vs[i]}; } return obj; } @Test(dataProvider="dataProvider") public void testDemo(TestEnum te){ System.out.println(te.getRetCode()); System.out.println(te.getMsg()); } }