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

Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM.

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/

Use this tool to look at the contents of GitHub and classify code based on the programming language used.  Content provided by IBM Developer.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}