JAVA利用enum结合testng做数据驱动示例

时间:2023-11-19 09:48:02

  数据驱动是做自动化测试中很重要的一部分,数据源的方案也是百花八门了,比如利用外部文件,直接在@DataProvider中写死等等,我们今天介绍一下利用enum来做数据源,先来看一下enum的写法:

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());
} }

上述的代码也是可以直接运行的,运行完后,结果如下:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAccAAAEKCAIAAADo6AmPAAAPa0lEQVR4nO3dS3qrOhYGUI/LA2I8jMatGkLNwK3q1BBuN7fhGAvYAmFvv8Ja32kkCk85/o/AaOfwv///c/l3+s9/fwB4zEGqAiSSqgCZpCpAJqkKkEmqAmSSqgCZpCpAJqkKkEmqAmRaTNVzfzxcHPvz9kaA/VlI1XN/7E7Xr65peeoOh6L18mXYCLBHbXcAhtg8dcNg9DI87U6VRoBdakrVYQA6fHHqDodj33eHY38OG192AgAfpSFVZ9f3k5Fr2PiyEw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dd4MSjX65s0rVYr0FcZr8Xz/Rt/p0/dvFZrLVUrNRI2pup945jRHYD1UVq4k9ZUXeqQ9ZejqUOGHV5212+vcvMbgKPVfrdansJsh7NDHBeyeOMZ8XW2pWrT+6/8cTxavTdVKwX6okqA8V4qSwaaa7au9EGre8u5xG/4bT3fPFYNOrj95Why2eHQGXfXDhtn6/VAg0Oqn/tshPveM+KLPC9Vw0qAtYVDGwv0jSoBLu5lumS8yMtS9ZGPTCrHuann703VbS9Hm1N3OFSPfqMhyibJVmpK1fLY3npGfIesOwCzt1hcCfD2s5bfrc0F+sYbXnrXrx3CYlpN7s5VUrXtDkA1UttWrwwhN/X8/LiDIoqVDtnwcrSd0aQA5f13VIp+uB5H0Nf1VG0M4UfOiD9q+6dVt6vLcWTNHh+JKgHWa/GFmgr0jbZZuWMQfIi1vOvwynpYvzijx1J19rHaeKjd9JadL9Lc8/HLEZ1m5VbDppejMRZrzyG1dEj8oNnk9vBlu+G5h+Uvn3ZG/FHmVn0sA5uJF3RIxoNq7J5U/USXwY2BzeBVHSJVSSBVYSBVSSBVATJJVYBMUhUgk1QFyCRVATJJVYBMUhUgUz1Vw8mUGjVq/PZGnsxYFSCTsapGjTtr5MmMVQEySVWATFIVIJNUBcgkVQEySVWATFIVIJNUBcgkVQEySVWATP8Cu7SPwQcF15wAAAAASUVORK5CYII=" alt="" />

利用上述方式最大的好处是把数据本身与持久化的对象放在一个地方了,且调用时,也很方便。

其实,利用外部文件的话,也可以数据对象持久化,只是原来的示例中我放在了一个Map中,同样可以把Map改为一个pojo对象,调用时也会很方便。

至于哪种方式好,大家自行的去体验,自行的去实现吧!