代码之家  ›  专栏  ›  技术社区  ›  Yoda ESG

在E2E测试中,如何处理(而不是解决)有时在表单提交后添加到表单中的验证码?

  •  0
  • Yoda ESG  · 技术社区  · 6 年前

    在我正在测试的系统中,captcha很少出现,但是当它出现时,在我提交表单之后,它就突然出现了(我猜不出是什么时候)。表单数据被保留,用户只需要解决验证码(解决在我的情况下不是问题)。 问题是我不知道验证码什么时候出现,只是盲目地在 [AfterStep] 钩子射在脚上,因为它会挡住每一步,等待时间很长。

    我的解决方案是:

    1. 在确认表单的每个步骤之后,我添加一个步骤 And Fill captcha if necessary

    Driver.FindElement 是一个阻塞调用,因此它将等待49*20秒等待永远不会出现的验证码。

    1. 浏览器获取HTTP代码 X

    这很糟糕,因为我发现没完没了的讨论都说Selenium不支持它,而且我听不到状态码,我认为这在最近一段时间没有改变。

    问题:

    0 回复  |  直到 6 年前
        1
  •  0
  •   Greg Burghardt    6 年前

    您需要一个专门检测和处理验证码的类,然后在每次与页面交互时委派给该类:

    class CaptchaHandler
    {
        readonly IWebDriver driver;
    
        private bool IsCaptchaVisible
        {
            get
            {
                // detect if captcha is visible
            }
        }
    
        internal CaptchaHandler(IWebDriver driver)
        {
            this.driver = driver;
        }
    
        internal void SolveCaptchaIfVisible(Action action)
        {
            try
            {
                action();
            }
            catch (WebDriverException)
            {
                if (IsCaptchaVisible)
                {
                    SolveCaptcha();
                    action();
                }
                else
                {
                    throw;
                }
            }
        }
    
        private bool SolveCaptcha()
        {
            // solve the captcha
        }
    }
    

    打个电话就行了 SolveCaptchaIfVisible

    var handler = new CaptchaHandler(driver);
    
    handler.SolveCaptchaIfVisible(() =>
    {
        // Do something that might fail because captcha is blocking
    });
    

    这也为您提供了一个优化验证码检测方式的地方。

    如果某些步骤似乎触发了验证码,请在步骤定义中初始化并使用该类。这种方法的好处是,如果需要用纯C#编写selenium测试,您可以重用它,而不必在中间使用小黄瓜层。