[英]Reading data from file using DataProvider in testng
假設我有一個包含以下數據的文本文件
username=testuser
password=testpassword
email=test@test.com
address=testaddress
zipcode=12345
或者我有一個包含以下數據的XML
<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
}
}
我的數據提供商可以從上述文本文件或XML中讀取值並將其提供給測試方法嗎?
根據我的理解,數據提供者將讀取文本文件中的所有行,並將其提供給測試方法,並拋出一條錯誤消息:“數據提供者試圖提供6個參數,但Test僅接受2個參數”?
請幫我。
是的,那是可能的。 您可以創建注釋來指定此DataProvider應該從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中以將其加載到另一個類,以便可以在其他測試中重用。
好友,您正在以錯誤的方式看數據提供者。 請參考testNG文檔。 http://testng.org/doc/documentation-main.html
您的目標可以通過以下代碼來實現。 Test
類包含測試方法。 它從另一個類TestData
指定的dataprovider獲取數據。 在TestData
類中,我們定義用於從文件/ xml訪問數據的方法,並將其作為“ @DataProvider”方法中的“ Object [] []”返回
public class Test {
@Test(dataProvider="testData" dataProviderclass = TestData.class)
public void userTest(TestData testData) {
//Test code goes here
}
}
public class TestData {
private String username;
private String password;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
@DataProvider(name="testData")
public static Object[][] userTestData (TestData testData) {
//Code to read from file/xml
TestData testData = new TestData();
testData.setUsername("Get from file/xml");
testData.setPassword("Get from file/xml")
return new Object{{testData}}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.