我想比较网址并打印,所以我使用了下面的代码。但它比较了整个网址,如下所示
对以下网址进行的实际比较:
https://accounts.google.com/signin/v2/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1<mpl=default<mplcache=
我使用过的代码:
String URL = driver.getCurrentUrl();
Assert.assertEquals(URL, "https://accounts.google.com" );
System.out.println(URL);
所需的解决方案:
我只想比较"https://accounts.google.com">
请帮助我解决这个问题
当您访问 url https://accounts.google.com
时,url 设置为:
https://accounts.google.com/signin/v2/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1<mpl=default<mplcache=
此网址本质上是动态的。因此,您将无法将assertEquals()
用作:
assertEquals()
定义为:void org.testng.Assert.assertEquals(String actual, String expected) Asserts that two Strings are equal. If they are not, an AssertionError is thrown. Parameters: actual the actual value expected the expected value
因此assertEquals()
将验证两个字符串是否相同。因此,您会看到错误。
溶液
要断言当前 url 中存在https://accounts.google.com
,您可以使用函数Assert.assertTrue()
如下所示:
String URL = driver.getCurrentUrl();
Assert.assertTrue(URL.contains("https://accounts.google.com"));
System.out.println(URL);
解释
assertTrue()
定义为:void org.testng.Assert.assertTrue(boolean condition) Asserts that a condition is true. If it isn't, an AssertionError is thrown. Parameters: condition the condition to evaluate
在您的情况下,您不应该使用"assertEquals",而应使用"assertTrue">
Assert.assertTrue(URL.startsWith("https://accounts.google.com"));
我使用了下面的代码,它对我来说工作正常
String URL = driver.getCurrentUrl();
if(URL.contains("url name"))
{
System.out.println("Landed in correct URL" +
"" + URL);
}else
{
System.out.println("Landed in wrong URL");
}
如果你想删除Assert.assertTrue并检查你的url,那么使用这个简单的技术,如下面的代码。断言等于,断言 Assert.assertTrue(url.equals("https://www.instagram.com/hiteshsingh00/?hl=en"));
也可以写成 Assert.assertEquals(true,url.equals("https://www.instagram.com/hiteshsingh00/?hl=en"));
也assertTrue(x == 2);
assertEquals(2,x);