BK Hasan
BK Hasan

Reputation: 119

junit Assert Equals

Problem: When doing the comparison, I get a fail trace error, but the expected and actual result is the same. I first get the output of the string, copied that from the console that is returned in eclipse, and used that string as the exact comparison. Is there an issue when there are new lines involved?

@Test
public void testErrorPage() throws InterruptedException{
    // Optional, if not specified, WebDriver will search your path for chromedriver.
    System.setProperty("webdriver.chrome.driver","C:\\Users\\HASANK\\Desktop\\tEST\\chromedriver.exe");

    ChromeOptions options = new ChromeOptions(); 
    options.addArguments("disable-infobars"); 
    WebDriver driver = new ChromeDriver(options);

    driver.get("http://thisisatest.com");
    Thread.sleep(3500);  // Let the user actually see something!

    String  error= driver.findElement(By.className("errorText")).getText();;
    System.out.println(error);

    String expectedTitle = "404\r\n" + 
            "The requested URL was not found on this server.";
  assertEquals(expectedTitle,error);
  driver.quit();
}

String that is returned from the gettext:

404

The requested URL was not found on this server.

Upvotes: 1

Views: 79

Answers (1)

GhostCat
GhostCat

Reputation: 140427

Most likely, the problem is here: "404\r\n": it is simply pretty easy to get such line break things wrong.

So the real answer is to avoid doing such exact equality comparisons. Instead, you could be doing

assertThat(actual, contains("whatever"))

where contains() would be a hamcrest matcher, that checks if "whatever" shows up somewhere in actual.

Of course, the downside of contains() is that it might lead to "false positives" when the string to match is "too generic". But on the other hand: contains() is also much more robust against changes. When you do exact matching, a tab-turned-into-a-space here, or an additional space/newline there breaks your exact match. And especially when testing "web output", you need to be robust. Otherwise you keep constantly updating your test cases because of subtle changes in the output.

Upvotes: 2

Related Questions