Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在评估断言之前失败testNG@Test_Java_Selenium_Selenium Webdriver_Webdriver_Testng - Fatal编程技术网

Java 在评估断言之前失败testNG@Test

Java 在评估断言之前失败testNG@Test,java,selenium,selenium-webdriver,webdriver,testng,Java,Selenium,Selenium Webdriver,Webdriver,Testng,如果在测试运行期间,任何测试步骤都抛出了一个异常,例如NoSuchElementException,那么我希望testNG测试(@test)失败。(举个例子) 在当前场景中,我正在检查是否单击某个特定任务,然后UI上的某个元素中会出现一些文本。但最近AUT在点击任务时抛出了一个网络错误,因此包含我正在验证的文本的元素没有出现在UI上。所以webdriver抛出了NoTouchElementException。但是,由于我的所有断言都在测试步骤的后面部分,TestNG将此测试标记为pass,因此也

如果在测试运行期间,任何测试步骤都抛出了一个异常,例如NoSuchElementException,那么我希望testNG测试(@test)失败。(举个例子)

在当前场景中,我正在检查是否单击某个特定任务,然后UI上的某个元素中会出现一些文本。但最近AUT在点击任务时抛出了一个网络错误,因此包含我正在验证的文本的元素没有出现在UI上。所以webdriver抛出了NoTouchElementException。但是,由于我的所有断言都在测试步骤的后面部分,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在本例中找不到元素,我故意在最大化代码后遗漏了一些文本,它将抛出NosTouchElementExeception,并且不会执行进一步的代码,这将导致断言未得到评估,测试用例执行将停止,而更多的测试用例依赖于此获取执行。以下是执行结果:-

org.openqa.selenium.NoSuchElementException:没有这样的元素:无法定位元素:{“方法”:“xpath”,“选择器”:“//h1[text()='Practice Automation']”

***元素信息:{Using=xpath,value=//h1[text()='Practice Automation']

默认套件

运行的测试总数:1,失败:0,跳过:0


退出代码为0的流程已完成此问题实际上取决于OP所需的行为

你的选择是: a) 对未能显示在UI上的元素放置另一个断言 (可能不理想,因为您希望验证针对给定原因而不是单个元素的测试,即成功登录而不是“单击登录按钮”

b) 使用testng注释来控制流和所需的行为
dependsOnMethods=“yourmethodcontainingtheelementthatcessuallyappears”

c) 避免捕获异常,这样testng将使该步骤失败(如果您也使用解决方案(b),将跳过其余的测试(用黄色表示)

d) 捕获SeleniumNoEmentException,然后对try/catch块中的elementPresent进行断言。通过相应地调整依赖项,您可以决定是希望脚本持久化还是跳过其余步骤

e) 使用softAssertion(这意味着如果元素在将来不再出现,您的测试不会失败,而是继续运行其余步骤)


希望这有帮助!

我怀疑测试中的代码被
try catch
块包围。如果您向方法定义中添加
抛出异常
,并且没有
try except
,则在抛出任何异常时,您可以获得标记为
Fail
的测试方法的行为,而不是
Pass
rt来自
断言

我尝试了以下代码,该代码抛出了
NoTouchElementException
(以模拟您的问题):

这里,由于类名为“something”的元素不存在,因此抛出
NoSuchElementException

Assert.assertEquals
未执行

TestNG将其标记为
失败
。这是您期望的行为吗

以下是完整的日志:

[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
试试这个:

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.");
}
这是一种廉价的黑客方式来做你正在尝试的事情,但它会起作用,并且会触发断言

您的try-catch块也是测试没有失败的原因。您通过捕获来处理测试中的失败

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

通过捕获,您实际上是在强迫测试通过。

如果出现错误,如果测试没有意义,那么它会自然而然地发出声音。@beforetest是解决方案吗?如果beforetest方法失败,这将跳过测试。您可以在
testng
测试的任何时候抛出异常。1.不要将测试代码放在
try exc下ept
块,因此将引发异常并将其提交给TestNG。然后TestNG可以将其标记为测试中的错误。2.重新访问您的断言,尽管存在网络错误,但这些断言仍获得成功(断言通过,我觉得可疑)@Naveen事实上,问题是断言没有得到完全评估,因为我提到我的断言在测试步骤的后面部分,这些步骤被跳过,因为我期待一个带有特定文本的webelement抛出NosTouchElementException,testNG继续执行测试套件中的下一个测试用例。那么,发生了什么d使用该测试方法?标记为通过/失败/错误?请共享测试方法代码。实际上,我正在寻找的是在任何测试步骤引发异常时使测试用例失败的机制。我已经使用了dependsOnMethods、DependsOnGroup、softAssertions等。对于选项a)您建议这将特别适用于该语句,但我正在寻找一种解决方案,如果任何测试步骤失败(抛出异常),则将测试标记为失败,而不管该特定步骤是否为断言。但这是标准的testNG行为(即,如果某个步骤失败,则整个测试用例标记为失败)。也许共享一些代码会有所帮助!:)我猜你已经在代码中使用了某种形式的try/catch,并且你正在捕获异常。这就是为什么你的测试被标记为通过的原因。让我试试这个。我已经编辑了这个问题,我想你已经纠正了我正确面对的问题。
try{
    testThisSteps();
}catch(Exception e){
    // you caught the failure. No error will pop up because it was caught
    e.printStackTrace();
}