英文:
java.lang.NullPointerException in click event on Selenium WebDriver com Java
问题
public void clicarNovoFuncionario() {
driver.findElement(btn_novo_funcionario).click();
}
public void escreverNomeFuncionario(String nome) {
driver.findElement(txt_nome_funcionario).sendKeys(nome);
}
public void escreverNumeroCpf(String cpf) {
driver.findElement(txt_cpf).sendKeys(cpf);
}
public void selecionarSexo(int index) {
WebElement elemento = driver.findElement(txt_sexo);
Select combo = new Select(elemento);
combo.selectByIndex(index);
}
public void escreverDataDeAdmissao(String data) {
driver.findElement(txt_data_admmissao).sendKeys(data);
}
public void escreverCargo(String cargo) {
driver.findElement(txt_cargo).sendKeys(cargo);
}
public void escreverSalario(String salario) {
driver.findElement(txt_salario).sendKeys(salario);
}
public void clicarTipoContratacao() {
driver.findElement(btn_tipo_contratacao).click();
}
public void clicarBotaoEnviar() {
driver.findElement(btn_enviar).click();
}
public void validarCadastroComSucesso(String cadastrado) {
String mensagem = driver.findElement(txt_cadastrao_sucesso).getText();
Assert.assertTrue(mensagem.contains(cadastrado));
}
public void clicarBotaoEdit() {
driver.findElement(btn_edit).click();
}
public void validarTelaEditVisivel() {
driver.findElement(txt_validar_tela_edit_disponivel).isDisplayed();
}
public void alterarCargo(String novoCargo) {
driver.findElement(txt_alterar_cargo).clear();
driver.findElement(txt_alterar_cargo).sendKeys(novoCargo);
}
public void confirmarDadosEditados() {
driver.findElement(btn_enviar).click();
}
public void validarAlteraçãoDosDadosFuncionario(String atualizada) {
driver.findElement(btn_enviar).click();
String mensagem = driver.findElement(txt_validar_alteracao_cargo).getText();
Assert.assertTrue(mensagem.contains(atualizada));
}
public void clicarExcluirFuncionario() {
driver.findElement(btn_excluir_funcionario).click();
}
public void validarExclusaoFuncionario(String removido) {
String mensagem = driver.findElement(txt_validar_exclusao_funcionario).getText();
Assert.assertTrue(mensagem.contains("removido"));
}
public class CrudFuncSteps {
WebDriver driver = null;
CrudFuncPage crud;
@Dado("que eu logue no sistema")
public void queEuLogueNoSistema() {
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.inmrobo.tk/accounts/login/");
driver.findElement(By.name("username")).sendKeys("LeandroPereira");
driver.findElement(By.name("pass")).sendKeys("123");
driver.findElement(By.xpath("//button[@class='login100-form-btn']")).click();
}
@Quando("eu clicar na opção Novo Funcionário")
public void euClicarNaOpçãoNovoFuncionário() {
crud = new CrudFuncPage(driver);
crud.clicarNovoFuncionario();
}
@Quando("informar o nome")
public void informarONome() {
crud.escreverNomeFuncionario("Carlos Antonio");
}
// ... (remaining code)
}
Note: The code provided here is a direct translation of the relevant parts of your original content. If you encounter any errors or issues, please review the translation and ensure it fits properly within your context.
英文:
I am receiving the error message from java.lang.NullPointerException in the click () event of SeleniumWebDriver, when I try to edit a previously registered record. The strange thing is that the script works perfectly up to a specific point which is Click (). During the execution I use the same click event on other elements without a problem. From the error message, it looks like I'm passing some null value but I don't know at what point. Can someone who has had the same problem help?
Below is the code of the classes used in automation.
Class RunCucumberTest
@RunWith(Cucumber.class)
@CucumberOptions(
features = "src/test/resources/features/CrudFuncSteps.feature",
glue = "br.com.inmetrics.teste.steps",
tags = {"~@ignore"},
plugin = {"pretty","html:target/report-html", "json:target/report-json"},
monochrome = true,
snippets=SnippetType.CAMELCASE,
dryRun = false,
strict = false
)
public class RunCucumberTest {
}
Class CrudFuncPage
public class CrudFuncPage {
WebDriver driver;
public CrudFuncPage(WebDriver driver) {
this.driver = driver;
}
private By btn_novo_funcionario = By.xpath("//*[@id=\"navbarSupportedContent\"]/ul/li[2]/a");
private By txt_nome_funcionario = By.id("inputNome");
private By txt_cpf = By.id("cpf");
private By txt_sexo = By.id("slctSexo");
private By txt_data_admmissao = By.id("inputAdmissao");
private By txt_cargo = By.id("inputCargo");
private By txt_salario = By.id("dinheiro");
private By btn_tipo_contratacao = By.id("clt");
private By btn_enviar = By.xpath("//input[@type='submit']");
private By txt_cadastrao_sucesso = By.xpath("//div[@class='alert alert-success alert-dismissible fade show']");
private By btn_edit = By.xpath("//table[@id='tabela']/tbody/tr/td[6]/a[2]/button/span");
private By txt_validar_tela_edit_disponivel = By.xpath("//input[@type='submit']");
private By txt_alterar_cargo = By.id("inputCargo");
private By txt_validar_alteracao_cargo = By.xpath("\"//div[@class='alert alert-success alert-dismissible fade show']\"");
private By btn_excluir_funcionario = By.id("delete-btn");
private By txt_validar_exclusao_funcionario = By
.xpath("//div[@class='alert alert-success alert-dismissible fade show']");
public void clicarNovoFuncionario() {
driver.findElement(btn_novo_funcionario).click();
}
public void escreverNomeFuncionario(String nome) {
driver.findElement(txt_nome_funcionario).sendKeys(nome);
}
public void escreverNumeroCpf(String cpf) {
driver.findElement(txt_cpf).sendKeys(cpf);
}
public void selecionarSexo(int index) {
WebElement elemento = driver.findElement(txt_sexo);
Select combo = new Select(elemento);
combo.selectByIndex(index);
}
public void escreverDataDeAdmissao(String data) {
driver.findElement(txt_data_admmissao).sendKeys(data);
}
public void escreverCargo(String cargo) {
driver.findElement(txt_cargo).sendKeys(cargo);
}
public void escreverSalario(String salario) {
driver.findElement(txt_salario).sendKeys(salario);
}
public void clicarTipoContratacao() {
driver.findElement(btn_tipo_contratacao).click();
}
public void clicarBotaoEnviar() {
driver.findElement(btn_enviar).click();
}
public void validarCadastroComSucesso(String cadastrado) {
String mensagem = driver.findElement(txt_cadastrao_sucesso).getText();
Assert.assertTrue(mensagem.contains(cadastrado));
}
public void clicarBotaoEdit() {
driver.findElement(btn_edit).click();
}
public void validarTelaEditVisivel() {
driver.findElement(txt_validar_tela_edit_disponivel).isDisplayed();
}
public void alterarCargo(String novoCargo) {
driver.findElement(txt_alterar_cargo).clear();
driver.findElement(txt_alterar_cargo).sendKeys(novoCargo);
}
public void confirmarDadosEditados() {
driver.findElement(btn_enviar).click();
}
public void validarAlteraçãoDosDadosFuncionario(String atualizada) {
driver.findElement(btn_enviar).click();
String mensagem = driver.findElement(txt_validar_alteracao_cargo).getText();
Assert.assertTrue(mensagem.contains(atualizada));
}
public void clicarExcluirFuncionario() {
driver.findElement(btn_excluir_funcionario).click();
}
public void validarExclusaoFuncionario(String removido) {
String mensagem = driver.findElement(txt_validar_exclusao_funcionario).getText();
Assert.assertTrue(mensagem.contains("removido"));
}
}
Class CrudFuncSteps
public class CrudFuncSteps {
WebDriver driver=null;
CrudFuncPage crud;
@Dado("que eu logue no sistema")
public void queEuLogueNoSistema() {
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.inmrobo.tk/accounts/login/");
driver.findElement(By.name("username")).sendKeys("LeandroPereira");
driver.findElement(By.name("pass")).sendKeys("123");
driver.findElement(By.xpath("//button[@class='login100-form-btn']")).click();
}
@Quando("eu clicar na opção Novo Funcionário")
public void euClicarNaOpçãoNovoFuncionário() {
crud = new CrudFuncPage(driver);
crud.clicarNovoFuncionario();
}
@Quando("informar o nome")
public void informarONome() {
crud.escreverNomeFuncionario("Carlos Antonio");
}
@Quando("informar o cpf")
public void informarOCpf() {
crud.escreverNumeroCpf("075.216.116-40");
}
@Quando("informar o sexo")
public void informarOSexo() {
crud.selecionarSexo(3);
}
@Quando("informar a data de admissao")
public void informarADataDeAdmissao() {
crud.escreverDataDeAdmissao("25/07/2000");
}
@Quando("informar o cargo")
public void informarOCargo() {
crud.escreverCargo("Analista de Testes");
}
@Quando("informar o salario")
public void informarOSalario() {
crud.escreverSalario("10000");
}
@Quando("selecionar o tipo de contratação")
public void selecionar_o_tipo_de_contratação() {
crud.clicarTipoContratacao();
}
@Quando("clicar no botão enviar")
public void clicarNoBotãoEnviar() {
crud.clicarBotaoEnviar();
}
@Então("o funcionário será cadastrador com sucesso")
public void o_funcionário_será_cadastrador_com_sucesso() {
crud.validarCadastroComSucesso("cadastrado");
}
@Quando("eu clicar na opção edit")
public void euClicarNaOpçãoEdit() {
//System.out.println("driver=" + driver);
crud.clicarBotaoEdit();
}
@Então("a tela para editar o funcionário será exibida")
public void aTelaParaEditarOFuncionárioSeráExibida() {
crud.validarTelaEditVisivel();
}
@Quando("alterar o cargo para Analista de Testes Automatizados")
public void alterarOCargoParaAnalistaDeTestesAutomatizados() {
crud.alterarCargo("Analista de Testes Automatizados");
}
@Quando("clicar em enviar")
public void clicarEmEnviar() {
crud.clicarBotaoEnviar();
}
@Então("o cargo será atualizado com sucesso")
public void oCargoSeráAtualizadoComSucesso() {
crud.validarAlteraçãoDosDadosFuncionario("atualizadas");
}
@Quando("eu clicar na opção excluir")
public void euClicarNaOpçãoExcluir() {
crud.clicarExcluirFuncionario();
}
@Então("o sistema exclui o funcionário com sucesso")
public void oSistemaExcluiOFuncionárioComSucesso() {
crud.validarExclusaoFuncionario("removido");
}
@After(order = 1)
public void screenshot(Scenario cenario) {
File file = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(file, new File("target\\screenshot\\"+cenario.getName()+".jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@After (order = 0)
public void fecharBrowser() {
driver.quit();
}
}
Print with errors
答案1
得分: 0
我个人认为问题出在你的变量上...更具体地说...
WebDriver driver=null;
CrudFuncPage crud;
后面是一些函数...
crud = new CrudFuncPage(driver);
crud.clicarNovoFuncionario();
仔细看的话,你只是创建了一个新对象...webdriver也是一样的...
这个实际上是一样的,你只是指定了一个null。
WebDriver driver=null; == WebDriver driver;
CrudFuncPage crud;
我的建议是:
WebDriver driver = new ChromeDriver();
CrudFuncPage crud = new CrudFuncPage(init_driver());
// 我不确定你是否可以在这里直接输入 ^ CrudFuncPage(driver);
public WebDriver init_driver()
{
return driver;
}
通过这样做,你将避免出现null的问题...另外,如果你没有使用线程,我建议将driver设置为静态的...以确保是同一个driver(通过将它设置为静态,你可以在"CrudFuncPage"
中这样做:
WebDriver driver = CrudFuncSteps.driver;
或者你可以直接从"CrudFuncSteps"
中导入那个driver
希望这能解决你的问题...因为看起来,根据我的看法,应该不会有问题...(我没有使用过cucumber,所以希望在这些更改后能正常运行)
此外,像这样的代码存在很多问题...
- 我不知道为什么你有西班牙装饰符...最好的编码方式是使用英语,以避免这样的问题(我个人不知道这些装饰符中是什么)
- 虽然你提供了那些截屏,但下次请为它们添加一些上下文...我个人不知道倒数第二个截屏是在哪里...
附注 - 如果你有任何问题,请告诉我 ...如果我知道答案,我会很乐意帮助你。
英文:
I personally think that the problem is in your variables ... to be more specific ...
WebDriver driver=null;
CrudFuncPage crud;
Later is somekinda function ...
crud = new CrudFuncPage(driver);
crud.clicarNovoFuncionario();
If you look closely ... you are just creating a new object ... same with webdriver ...
This one is acctually the same, all you did was that you specified that there is a null.
WebDriver driver=null; == WebDriver driver;
CrudFuncPage crud;
My recommendation:
WebDriver driver = new ChromeDriver();
CrudFuncPage crud = new CrudFuncPage(init_driver());
// I am not sure if you can just type here ^ CrudFuncPage(driver);
public WebDriver init_driver()
{
return driver;
}
by doing this, you will avoid having problems with the null ... also, if you are not using Threads, I would recommend making that driver static ... to be 100% sure that its going to be the same driver (by making it static, you can then do something like this in "CrudFuncPage"
:
WebDriver driver = CrudFuncSteps.driver;
or you just import that driver directly from "CrudFuncSteps"
Hopefully it will fix your problem ... because by looking at it, i think there should not be a problem ... (I did not work with cucumber, so hopefully it will be fine after these changes)
Also, there is quite a few problem with a code like this...
- I have no idea why do you have spanish decorators ... The best way to code is to use english, to avoid problems like this (i personally have no idea what is in those decorators)
- Its nice that you provided those screenshots, but next time, please add some context to them ... i personally dont know where there is the second to last one...
P.S -> if you have any question, please let me know ... If I will know the answer, I will gladly help.
专注分享java语言的经验与见解,让所有开发者获益!
评论