无法通过 try/catch 获取自定义类函数来工作

问题描述 投票:0回答:1

我无法让自定义类函数正常工作。当调用类中的版本时,try and catch 不会触发。如果我在测试文件中移动该函数,它就会按预期工作。

在我的示例中,它应该触发

NoSuchElementException
catch 块,但当我运行测试时,我看到错误弹出窗口。它甚至不会触发通用的
Exception
catch 块。

compose.json

"php-webdriver/webdriver": "^1.15",
"phpunit/phpunit": "~8.5.0 || ^9.3",
"phpunit/phpunit-selenium": "^9.0",

自定义

TestCase
类,具有函数
existsById()
/plugins/MyPlugin/src/Tests/TestCase.php

<?php declare(strict_types=1);

namespace MyPlugin\Tests;

use PHPUnit\Framework\TestCase as MyPluginTestCase;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Cake\Datasource\ConnectionManager;

class TestCase extends MyPluginTestCase
{

    // other functions and code
    // $this->driver is initialized and references in other functions

    // confirm element with ID specific exists
    protected function existsById($id) {
        $d = 0;

        try
        {
            $this->driver->findElement(WebDriverBy::id($id));
        }
        catch(Facebook\WebDriver\Exception\NoSuchElementException $e)
        {
            $d++;
        }
        catch(Exception $f){
            $d++;
        }

        return ($d == 0 ? true : false);
    }
}
?>

PHPUnit 测试文件:

/tests/escalationStageResolveTest.php

<?php
use MyPlugin\Tests\TestCase;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverSelect;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\Chrome\ChromeDriver;
use Facebook\WebDriver\Chrome\ChromeOptions;

class escalationStageResolveTest extends TestCase
{
    /**
     * @var RemoteWebDriver
     */
    protected $driver;

    //..
    public function testSLStageResolve() 
    {
        //...
        $this->assertEquals(false, $this->existsById("accordion-result-63080"));
    }

    // uncomment and it works
    /*
    protected function existsById($id) {
        $d = 0;

        try
        {
            $this->driver->findElement(WebDriverBy::id($id));
        }
        catch(Facebook\WebDriver\Exception\NoSuchElementException $e)
        {
            $d++;
        }
        catch(Exception $f)
        {
            $d++;
        }

        return ($d == 0 ? true : false);
    }*/

}
?>
php selenium-webdriver phpunit cakephp-4.x
1个回答
0
投票

解决方案:将缺少的反斜杠添加到

catch
中正在寻找的类中。

原文:

Facebook\WebDriver\Exception\NoSuchElementException $e

工作:

\Facebook\WebDriver\Exception\NoSuchElementException $e

如果没有反斜杠,它会在插件中寻找该类,而该类显然不存在。

© www.soinside.com 2019 - 2024. All rights reserved.