使用testng中的DataProvider从文件中读取数据 [英] Reading data from file using DataProvider in testng

查看:310
本文介绍了使用testng中的DataProvider从文件中读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含以下数据的文本文件

Let's say I have a text file with the following data

username=testuser
password=testpassword
email=test@test.com
address=testaddress
zipcode=12345

或者我有一个包含以下数据的XML

Or I have an XML with the following data

<TestData>
   <UserInfo>
       <username>testuser</username>
       <password>testpassword</password>
       <email>test@test.com</email>
       <address>testaddress</address>
   </UserInfo>
</TestData>

我的测试如下

public class DPTest {

   @Test(dataprovider="testdp")
   public void userTest_01(String username, String Password) {

   //Test goes here

   }
}

另一个类

public class DPTest2 {

   @Test(dataprovider="testdp")
   public void userTest_02(String email, String address, String password) {

   //Test goes here

   }
}

我的dataprovider可以读取上述文本文件或XML中的值并将其提供给测试方法吗?

Can my dataprovider read the values from the above mentioned text file or XML and supply it to the test methods?

根据我的理解,数据提供者将读取文本文件中的所有行并将其提供给测试方法,并抛出错误说数据提供者试图提供6个参数但测试只能接受2个参数?

As per my understanding the data provider is going to read all the lines in the text file and supply it to the test method and throw an error saying "data provider is trying to provide 6 parameters but Test can only accept 2 parameter" ?

请帮帮我。

推荐答案

是的,这是可能的。
您可以创建一个注释来指定此DataProvider应从XML加载的参数。

Yes, that's possible. You can create an annotation to specify the parameters this DataProvider should load from your XML.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface XmlParameters {
   String[] value();    
}

@Test(dataProvider = "XMLFileLoader")
@XmlParameters({"username", "password"})
public void testSomething(String username, String password) {
    // implementation omitted for brevity
}

@DataProvider(name = "XMLFileLoader")
public static Object[][] getDataFromXmlFile(final Method testMethod) {
    XmlParameters parameters = testMethod.getAnnotation(XmlParameters.class);
    String[] fields = parameters.value();
    //load just the fields you want
    return new Object[][] { { "user1", "pass1" } };
}

此代码不是生产就绪,您应检查注释是否为在读取值之前不是null,并且可能更好地移动接口和逻辑以将xml加载到另一个类,因此您可以在另一个测试中重用。

This code is not "production ready", you should check if the annotation is not null before reading the values, and is probably better move the interface and the logic to load your xml to another class, so you can reuse on another tests.

这篇关于使用testng中的DataProvider从文件中读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆