fail testng@test在评估Assert之前

rlcwz9us  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(346)

如果在测试运行期间任何一个测试步骤抛出一个异常,比如nosuchelementexception,那么我希望testng测试(@test)失败(举个例子)
在当前场景中,我正在检查是否单击某个特定任务,然后ui上的某个元素中会出现一些文本。但是最近aut在单击任务时抛出了一个网络错误,因此包含我正在验证的文本的元素没有出现在ui上。所以webdriver抛出了nosuchelementexception。但是由于我所有的Assert都在测试步骤的后面部分,testng将这个测试标记为pass,因此也继续执行依赖的测试用例。
那么,如果测试中的所有步骤都没有执行,或者抛出了任何异常,那么有没有办法使测试失败呢?
以下是示例代码:

public class DummyTest {

@Test
public void testThis(){
    try{
        testThisSteps();
    }catch(Exception e){
        e.printStackTrace();
    }
}

public void testThisSteps() throws Exception{
    System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("http://toolsqa.com/automation-practice-form/");
    driver.manage().window().maximize();
    driver.findElement(By.xpath("//h1[text()='Practice Automation']"));
    int i = driver.findElements(By.name("firstname")).size();
    Assert.assertTrue(i!=0,"Element does not exist even though page is loaded");
  }
}

现在的问题是,如果webdriver找不到元素,在这个例子中,我故意在maximuze代码之后遗漏了一些文本,它将抛出nosuchelementexeception,并且不会执行进一步的代码,这将导致Assert没有得到评估,并且测试用例的执行将停止,而更多的测试用例依赖于这个获取执行。这是死刑result:-
org.openqa.selenium.nosuchelementexception:没有这样的元素:找不到元素:{“method”:“xpath”,“selector”:“//h1[text()='practice automation']”

***元素信息:{using=xpath,value=//h1[text()='practice automation']

默认套件
运行的测试总数:1,失败数:0,跳过数:0
进程已完成,退出代码为0

twh00eeo

twh00eeo1#

这个问题实际上取决于op所要求的行为。
您的选项是:a)对未能出现在ui上的元素添加另一个Assert(可能不理想,因为您希望验证针对给定原因而不是单个元素的测试,即成功登录而不是“单击登录按钮”
b) 使用testng注解来控制流和所需的行为 dependsOnMethods="yourMethodContainingTheElementThatOccassionallyAppears" c) 避免捕获异常,这样testng将使该步骤失败(如果您也使用解决方案(b),则将跳过其余的测试(用黄色表示)
d) 捕获seleniumnoementexception,然后对try/catch块中的elementpresent进行Assert。通过相应地调整依赖关系,您可以决定是希望脚本持久化还是跳过其余步骤。
e) 使用softassertion(意思是如果元素在将来不再出现,那么测试不会失败,而是继续运行其余的步骤)
希望这有帮助!

1qczuiv0

1qczuiv02#

我怀疑测试中的代码,被 try-catch 阻止。如果你加上 throws Exception 方法定义和否 try-except ,您可以得到标记为 Fail ,而不是 Pass 当任何异常从 Assertions .
我尝试了以下代码 NoSuchElementException (模拟你的问题):

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

import org.testng.annotations.Test;
import org.testng.asserts.Assertion;

public class SeleniumTests {

    @Test()
    public void testmethod() throws  Exception{
        WebDriver driver = new ChromeDriver();
        driver.get("http://www.google.com");
        driver.findElement(By.className("something")); // throws NoSuchElementException
        Assert.assertEquals(true, false);
        driver.quit();
    }

}

这里,作为具有类名的元素 "something" 不存在,抛出 NoSuchElementException . Assert.assertEquals 未执行。
testng将其标记为 Failed . 这是你期望的行为吗?
以下是完整的日志:

[TestNG] Running:
  C:\Users\USER_HP_2013_03\AppData\Local\Temp\testng-eclipse--1064112655\testng-customsuite.xml

Starting ChromeDriver 2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed) on port 10078
Only local connections are allowed.
Jan 04, 2017 5:10:03 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
Jan 04, 2017 5:10:06 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
FAILED: testmethod
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"class name","selector":"something"}
  (Session info: chrome=55.0.2883.87)
  (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 42 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:48:19 -0700'
System info: host: 'HP201303', ip: '192.168.56.1', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_73'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed), userDataDir=C:\Users\USER_H~1\AppData\Local\Temp\scoped_dir5260_26036}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=55.0.2883.87, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: 92cbb27a874d7d2215eee51fc6a77819

***Element info: {Using=class name, value=something}

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:635)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:368)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByClassName(RemoteWebDriver.java:457)
    at org.openqa.selenium.By$ByClassName.findElement(By.java:391)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:360)
    at SeleniumTests.testmethod(SeleniumTests.java:14)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)

===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================

[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@35bbe5e8: 9 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@2a18f23c: 12 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@4ec6a292: 27 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@3f0ee7cb: 9 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 4 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@66d33a: 8 ms
lmvvr0a8

lmvvr0a83#

试试这个:

try {
    driver.findElement(by.xpath("//h1[text()='Practice Automation']");
}catch (org.openqa.selenium.NoSuchElementException e){
     assert.fail("the element I was attempting to location was not found.");
}

这是一个廉价的黑客方式做什么,你正在尝试,但它会工作,并Assert将触发。
此外,try-catch块也是测试没有失败的原因。你抓住了考试的失败,就是在处理它

try{
    testThisSteps();
}catch(Exception e){
    // you caught the failure. No error will pop up because it was caught
    e.printStackTrace();
}

抓住你就等于迫使考试通过。

相关问题