System.Reflection.TargetInvocationException :调用的目标已抛出异常

IT技术 c# reactjs selenium selenium-webdriver protractor-net
2021-05-17 05:01:21

我正在尝试自动化 reactjs 应用程序和我们的项目使用的框架,该框架基于 C# 和量角器网络构建。

在任何单击或断言函数后,我收到以下错误,但代码中定义的操作成功执行。

System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
  ----> OpenQA.Selenium.WebDriverTimeoutException : timeout

这个错误的原因是什么?

    using NUnit.Framework;
    using OpenQA.Selenium;
    using OpenQA.Selenium.Interactions;
    using OpenQA.Selenium.Support.PageObjects;
    using OpenQA.Selenium.Support.UI;
    using Protractor;
    using System;
    using System.Collections.Generic;


    public Class personalinformations
    {

    private NgWebDriver _ngdriver;


            public PersonalInformations(IWebDriver driver)
            {

                _ngdriver = new NgWebDriver(driver);
                PageFactory.InitElements(_ngdriver, this);
                _ngdriver.IgnoreSynchronization = true;

            }

     [FindsBy(How = How.Id, Using = "btnSubmit")]
            private IWebElement btnsave { get; set; }

     public void saveSection()
            {
WebDriverWait wait = new WebDriverWait(ngdriver, TimeSpan.FromSeconds(30));         
           wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*@id='btnSubmit']"));

btnsave.Click();
    }
}

注意:虽然使用 Thread.Sleep(1000) 等待有时代码有效。我也尝试使用 Javascript 单击元素,结果是相同的。

2个回答

通过WebDriverWaitExpectedConditions方法ElementIsVisible等待元素后,您将在下一步中调用,Click()因此您需要调用ElementToBeClickable方法而不是ElementIsVisible方法,如下所示:

public void saveSection()
{
    WebDriverWait wait = new WebDriverWait(ngdriver, TimeSpan.FromSeconds(30));         
    wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//*@id='btnSubmit']"));
    btnsave.Click();
}

这是一个有趣的异常:“System.Reflection.TargetInvocationException:调用的目标已抛出异常。”; 我遇到了好几次,但我搜索了这篇文章“调用的目标已抛出异常”错误(mscorlib), 他们说你应该检查这个异常背后的根本原因。所以我加了一个

尝试 {element.Click();} catch(Exception e){Console.WriteLine(e);}

然后异常似乎逃脱了......