java 如果其他条件 Assert.assertEquals selenium testNG
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34891265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
if else condition on Assert.assertEquals selenium testNG
提问by Syafriadi Hidayat
I am working on selenium and testNG with java.. I have some problem about this code:
我正在使用 java 处理 selenium 和 testNG .. 我对这段代码有一些问题:
Assert.assertEquals(webDriver.getCurrentUrl(), "http://google.com");
the question is how to create if else condition in assertEquals. like this
问题是如何在 assertEquals 中创建 if else 条件。像这样
if( Assert.assertEquals(webDriver.getCurrentUrl(), "http://google.com"));
{
//do Nothing
}
else
{
// take screenshoot
}
any idea guys?
有什么想法吗?
回答by niharika_neo
If an assert fails, it throws an assertionError. You need to catch the AssertionError and in the catch capture the screenshot.
如果断言失败,它会抛出一个 assertionError。您需要捕获 AssertionError 并在捕获中捕获屏幕截图。
try{
Assert.assertEquals(...,...);
}catch(AssertionError e){
Log error;
Takescreenshot;
}
回答by Wael Said Emara
string url = webDriver.getCurrentUrl();
if(url == "http://google.com")
{
// take screenshoot
}
Assert.assertEquals(url, "http://google.com")
回答by Guy
If the condition in Assert.assertEquals()
is false, for example Assert.assertEquals("qwerty", "asdfgh")
, the test will terminate, so there is no point to put it in if
statement.
Assert.assertEquals()
例如Assert.assertEquals("qwerty", "asdfgh")
,如果条件为假,则测试将终止,因此将其放入if
语句中没有意义。
If you want the test to to take screenshot in failure you can write your on assertEquals
implementation
如果您希望测试在失败时截取屏幕截图,您可以编写您的assertEquals
实现
public static class Assert
{
public static void assertEquals(Object actualResult, Object expectedResult, boolean stopOnError = true)
{
if (!expectedResult.equals(actualResult))
{
// take screenshot
if (stopOnError)
{
throw new Exception();
}
}
}
}
And then simply do
然后简单地做
Assert.assertEquals(webDriver.getCurrentUrl(), "http://google.com"));
You can also change stopOnError
to false to prevent test termination when they are not equal.
您还可以更改stopOnError
为 false 以防止在它们不相等时终止测试。
If you don't want the test to end if the URL is wrong simply do
如果您不希望在 URL 错误的情况下结束测试,只需执行
if (!webDriver.getCurrentUrl().equals("http://google.com"))
{
// take screenshot
}