比较整个 url 到 Assert.assertEquals

Comparing entire url through Assert.assertEquals

我想比较url并打印,所以我使用了下面的代码。但它正在比较整个 url 如下

下面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&ltmpl=default&ltmplcache=

我用过的代码:

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&ltmpl=default&ltmplcache= 

这个url本质上是动态。所以你将无法使用 assertEquals() as :

  • 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() 将验证两个 Strings 是否相同。因此您会看到错误。

解决方案

要在 当前 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");

    }