Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Unit Testing With Eclipse and Converting a Map to a String

DZone's Guide to

Unit Testing With Eclipse and Converting a Map to a String

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

When testing with JUnit, one often has to compare the expected result of a computation with the actual result. A convenient way of doing this is to turn the actual result into a string and then compare two strings. On one hand, the convenience is because converting the actual result to string is often simpler than constructing an object for the expected result (the final decision between these two options depends on which one of the two has applications beyond unit testing). On the other hand, Eclipse helps with string comparisons in two ways:

  • Preference “Java → Editor → Typing → Escape text when pasting into a string literal”: Allows one to quickly turn blocks of text into Java string literals for the expected result.
  • Built-in diff for assertEquals(): If assertEquals() fails for two strings, Eclipse shows a nice diff of the results. This makes it easy to figure out what went wrong.

Obviously, the output has to be deterministic which is a problem for, say, HashMaps. With this motivation in mind, now a question: What is the quickest way of turning a Map into a string where the keys are sorted?

public static <K extends Comparable<? super K>, V> String toStringSorted(
Map<K, V> map) {
return new TreeMap<K, V>(map).toString();
}

Select the text between the braces to make it visible

From http://2ality.blogspot.com/

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}