我有一个方法addNewUser,它要求用户提供用户名、电子邮件和密码。这些将存储在 Excel 工作表的相应列中。请参阅下面的代码:
public class ExcelConfig {
public FileInputStream fis;
public FileOutputStream fos;
public XSSFWorkbook wb;
public XSSFSheet sh;
public XSSFRow row;
public XSSFCell cell;
int lastRow = 0;
ConfigReader cr = new ConfigReader();
public ExcelConfig(){
try {
fis = new FileInputStream(cr.getExcelPath());
wb = new XSSFWorkbook(fis);
}
catch (Exception e) {
System.out.println("Error at ExcelConfig " + e.getMessage());
}
}
public void addNewUser(String un, String em, String pw){
cell = row.createCell(0);
cell.setCellValue(un);
cell = row.createCell(1);
cell.setCellValue(em);
cell = row.createCell(2);
cell.setCellValue(pw);
}
}
现在,在其他类中,我调用了 addNewuser 方法。请参阅下面的代码
public class NextStepTest {
WebDriver driver;
ConfigReader cf;
ExcelConfig ec;
UserDetails ud;
LandingPage lp;
RegisterPage rp;
String username;
String email;
String password;
@BeforeTest
public void setUp(){
cf = new ConfigReader();
ec = new ExcelConfig();
ud = new UserDetails();
driver = cf.getChromeDriver();
driver.get(cf.getAppUrl());
}
@Test
public void register(){
username = cf.getUsernameFromProperty();
email = cf.getEmailFromProperty();
password = ud.getPassword();
try{
lp = new LandingPage(driver);
lp = PageFactory.initElements(driver, LandingPage.class);
lp.locateRegisterLink();
lp.clickRegisterLink();
rp = new RegisterPage(driver);
rp = PageFactory.initElements(driver, RegisterPage.class);
rp.locateUsernameField();
rp.registerAccount(username, email, password);
ec.getSheet(0);
ec.getNextRow();
ec.addNewUser(username, email, password); // here I call addNewUser method that now has username, email and password values
ec.closeFile();
rp.logout();
lp.locateLoginLink();
}
catch(Exception e){
System.out.println("Error under NextStepTest.java => " + e.getMessage());
}
}
现在,我想问的是,是否可以使addNewUser方法参数动态化?我知道这种情况取决于项目。某些项目可能只需要用户名、电子邮件和密码(在这种情况下)即可在 Excel 上添加。如果以后的其他项目需要添加账户类型怎么办?因此参数现在将变为 4。或者其他项目只需要电子邮件和密码。我应该每次都更新 addNewUser 方法参数吗?我还是这门语言的初学者。任何帮助都可以。谢谢大家!
最佳答案
What if in the other future project , it will require to add an account type?
那么将来你需要重载该方法
public void addNewUser(String un, String em, String pw){
}
//only username
public void addNewUser(String un){
}
//with all the info + token
public void addNewUser(String un, String em, String pw, String token){
}
您唯一需要注意的是:这些都是字符串...所以您需要预先知道哪个字符串对应哪个参数...
关于JAVA:向方法添加新参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42411767/