Over a million developers have joined DZone.

Unit Testing With Eclipse and Converting a Map to a String

· Java Zone

Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience, brought to you in partnership with JetBrains

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/

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

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

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

{{ parent.tldr }}

{{ parent.urlSource.name }}