Search code examples
javastringjunitcompareassert

Compare strings that can come in a different internal order


I'm writing a JUnit test that check messages (one message per line) inside one unified String. The format is as follows:

[* Message for Alice *]

Hey, first message

Second message

[* Message for Jim *]

Holler

Are you there?

[* General Messages *]

Welcome everyone!

This is yet another message.

The problem is that the actual string's order that I receive may change (except for the General Messages that always comes at the end of the string). For example: one time I can get Jim's messages first, so when I try to use assertEquals() the test fails. Unfortunately I don't have access to the code that generate the messages, so I can't make any modifications.

What is the best way to compare these strings and validate that they're the same?


Solution

  • You should re-organize your tests to address arbitrary re-ordering, for example, like this:

    • Split the string into individual messages
    • Separate general messages and all other messages
    • Order expected and actual messages in the same order (e.g. alphabetical)
    • Compare ordered lists of expected and actual messages. Now that they are ordered the same, they should equal item-by-item
    • Check that the general messages come after all other messages in the actual message stream.