0

There is a string: "Login 1234 has been created" Here 1234 is a dynamic text. How can I compare this entire string in one shot.

I do know of the way to do split using " "(space) and then getting into array,asserting it using regex:

assertTrue(dynamicText.substring(1, 5).equals([0-9]+));

but that takes more lines of code. I want to know if there is any efficient way of coding other than this. Thanks.

codefemme
  • 63
  • 2
  • 11

3 Answers3

1

I found the solution:

String expected = "Login 1234 has been created";
        if(expected.matches("Login ([0-9]+) has been created"))
        {
            System.out.println("matched");
        }
codefemme
  • 63
  • 2
  • 11
0

There are primarily two assertions visible with your input:

  1. Asserting statics in the output

    assertTrue(dynamicText.contains("Login") && dynamicText.contains("has been created"));
    
  2. String userInput = "1234"; 
    // if there is a dynamic variable provided as an input this has to be there in your code somewhere
    
    assertTrue(dynamicText.substring(1, 5).equals(userInput));
    

The reason that the input has to be there is otherwise you would end up reading static text from WebElements found by you.

Hence in short

String expectedOutput = "Login " + userInput + " has been created.";
assertTrue("The expected output is different!", dynamicText.equals(expectedOutput));
Naman
  • 21,685
  • 24
  • 196
  • 332
  • How does this works when comparing the template `{"name" : "$name", "age" : "$age"}` with `{"name" : "Bob", "age" : 47}` at https://stackoverflow.com/questions/51146644/compare-dynamic-xml-json-content-with-static-payload – Kanagavelu Sugumar Jul 03 '18 at 04:52
0

Use regular expression:

if (s.matches("Login \\S+ has been created")) {
    // code here
}

If you need the login name, you can't use that convenience method, but have to use the Pattern class directly:

Pattern p = Pattern.compile("Login (\\S+) has been created");
Matcher m = p.matcher(s);
if (m.matches()) {
    String login = m.group(1);
    // code here
}
Andreas
  • 147,606
  • 10
  • 133
  • 220