Let’s say you encounter a situation where you have a Map of Maps where the nested Map has a value of Object. These were the cards I was dealt while refactoring a bit of code recently. This case may be a bit too generic and likely warrants a more specific domain object at the least; however, I maintained this structure to remain backward compatible I did some TDD to make sure nothing was broken by the refactoring.
There are many options for unit testing a Map of Maps, but I’m particularly more fond of the assertThat approach with Matchers. I will always strive to use these over the rudimentary assertEquals, assertTrue and assertFalse, which provides little value for reporting and troubleshooting. Hamcrest is one of those open-source libraries in Java that has become so popular that it has basically received the ultimate form of flattery in the newer versions of Java’s JUnit. Below you can find several examples of how to leverage JUnit to test Maps of Maps:
import org.hamcrest.CoreMatchers;
import org.hamcrest.collection.IsMapContaining;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
@RunWith(MockitoJUnitRunner.class)
public class MapOfMapTest {
@InjectMocks
private Processor processor;
@Test
public void testProcess_CloseIsTrue_ExpectTrue() throws Exception {
// setup
...
// when
...
// test
Map<String, Map<String, Object>> mapOfMaps = (Map<String, Map<String, Object>>) processor.process();
assertThat(mapOfMaps, is(notNullValue()));
Map<String, Object> cusipMap = new HashMap<>();
cusipMap.put("ticker", "BGNIXS");
String cusip = "091929695";
cusipMap.put("cusip", cusip);
cusipMap.put("name", "BlackRock GNMA Instl");
cusipMap.put("closed", true);
cusipMap.put("scale", 3);
Map<String, Object> actual = mapOfMaps.get(cusip);
compareMaps(mapOfMaps, cusipMap, cusip, actual);
}
protected void compareMaps(Map<String, Map<String, Object>> mapOfMaps, Map<String, Object> cusipMap, String cusip,
Map<String, Object> actual) {
// The most basic pure JUnit assertion, but probably the least preferred option. This is not expressive and will provide poor feedback on failure
assertTrue(actual.equals(cusipMap));
// The second most basic pure JUnit assertion, and only marginally better than the above. This is not expressive and will provide poor feedback on failure
assertEquals(actual, cusipMap);
// Mildly more expressive and would be preferred in my opinion over the above two options
assertThat(actual, is(cusipMap));
// ----------------------------------------------------------------------------------------------------
// Using Hamcrest CoreMatchers - more expressive than the above
assertThat(actual, CoreMatchers.<Map<String, Object>>equalTo(cusipMap));
// Using Hamcrest CoreMatchers - check a specific key and value and is more expressive than the above
assertThat(mapOfMaps, hasEntry(equalTo(cusip), CoreMatchers.<Map<String, Object>>equalTo(cusipMap)));
// ----------------------------------------------------------------------------------------------------
// Using Hamcrest: Ensure the key used for the outer map is present
assertThat(mapOfMaps, IsMapContaining.hasKey(cusip));
// Using Hamcrest: Ensure the actual inner Map value is present in the output Map ... this is obvious
assertThat(mapOfMaps, IsMapContaining.hasValue(actual));
// Using Hamcrest: Ensure the generated inner Map value is present in the output Map ... this is the more valid test
assertThat(mapOfMaps, IsMapContaining.hasValue(cusipMap));
// Using Hamcrest: Two for one assertion that takes care of checking the key and the value ... use this one
assertThat(mapOfMaps, IsMapContaining.hasEntry(cusip, cusipMap));
}
}
Needed to draft you one very small remark so as to thank you so much as before relating to the pretty techniques you’ve discussed above. It’s simply surprisingly generous of people like you to grant freely all a few individuals would have offered for sale for an electronic book to earn some profit for themselves, primarily since you might well have done it if you decided. Those creative ideas likewise acted like a great way to realize that other individuals have the same eagerness the same as my own to learn much more in respect of this condition. I’m certain there are thousands of more fun opportunities up front for people who take a look at your website.
My wife and i got absolutely excited Chris could round up his survey because of the ideas he made through your web pages. It is now and again perplexing to just be giving freely facts that a number of people could have been trying to sell. And now we see we now have the website owner to thank for this. Most of the illustrations you have made, the easy blog navigation, the relationships you will aid to create – it’s everything superb, and it’s making our son in addition to the family know that the theme is brilliant, and that is highly pressing. Thanks for the whole thing!
Thank you a lot for providing individuals with an extremely spectacular possiblity to read in detail from this web site. It is always very useful and jam-packed with amusement for me and my office peers to visit your website at least 3 times weekly to read through the latest tips you have got. And indeed, I’m actually fulfilled with all the effective solutions you give. Some 1 areas in this post are surely the most impressive we’ve had.
I in addition to my buddies were actually examining the best tips found on the blog and all of a sudden came up with a horrible suspicion I had not thanked the blog owner for those strategies. All the young men are already absolutely happy to learn them and already have unquestionably been using these things. Many thanks for getting well thoughtful as well as for making a decision on such marvelous subject areas millions of individuals are really desirous to discover. Our sincere regret for not expressing appreciation to you earlier.
FVqWmlrpuLSwiv
A masterpiece of writing! You’ve covered all bases with elegance.
You have a unique perspective that I find incredibly valuable. Thank you for sharing.
Your blog is a go-to resource for me. Thanks for all the hard work!
A masterpiece of writing! You’ve covered all bases with elegance.
I’m so grateful for the information you’ve shared. It’s been incredibly enlightening!
The Writing is a go-to resource, like a favorite coffee shop where the barista knows The order. Always comforting.
The insights light up my intellect like fireworks. Thanks for the show!
What a compelling enjoy reading! Your arguments were well-presented and convincing.
I admire the way you tackled this complex issue. Very enlightening!
Delightful read. The passion is visible, or at least, very well faked.
Articulated points with finesse, like a lawyer, but without the billable hours.
The grace and authority you handle topics with are as mesmerizing as a moonlit dance. I’m thoroughly impressed.
Each post you write is like a letter I’ve been waiting for. Always delivered with care.
The clarity of The writing is like a perfectly tuned instrument, making hard to understand melodies seem effortless.
Provoked thought and taught me something new, as if my brain needed more exercise.
The hard work you put into this post is as admirable as The commitment to high quality. It’s very attractive.
Learned a lot from this post, and here I was thinking I knew it all. Thanks for the humble pie.
The insights are as invigorating as a morning run, sparking new energy in my thoughts.
Every post of Thes is a learning opportunity for me. Thanks for sharing The expertise.
I’m so glad I stumbled upon this article. It was exactly what I needed to read!
The content is like a treasure chest; every post uncovers gems of wisdom. X marks the spot here.
Beautifully written and incredibly informative, The post has made a lasting impression on me. Thank you for sharing The thoughts.
This post was a joy to read from beginning to end! Your expertise on the subject shines through in every paragraph, making complex topics accessible and interesting. Your passion for the subject matter is infectious, and I can’t wait to see what topic you tackle next. Excellent job.
chauffeur service provided by airporttransferdfw.com for Dallas/Fort Worth International Airport. This service offers professional drivers and upscale vehicles, ensuring a luxurious and comfortable travel experience. Travelers can book this service to enjoy personalized chauffeur-driven transfers that prioritize punctuality and convenience.
We offer 24-hour reservations for our DFW Airport Limo service in the Dallas area with the latest technology to dispatch and contact your driver.
Elevate your experience with Miami’s finest limo services. From airport transfers to wedding extravaganzas, our luxury fleet and competitive rates ensure your journey is as memorable as the destination.
Airport Transfers Bahamas operates a luxury fleet of vehicles that provide the highest class in luxury comfort for our clients as well as the best in transportation vehicle safety.
Nassau Airport to The Cove Atlantis – We’re excited to be able to provide professional transportation services from Nassau Airport to The Cove Atlantis and Paradise Island!
Airport transfers service Nassau Bahamas providing express transportation (Private Hire), services for to and from Bahamas Airports, Bahamas Cruise Ports to and from anywhere in the Bahamas.
Reliable transportation from Waterloo to Pearson Airport is at your fingertips. Choose Waterloo Taxi for punctual and comfortable rides, whether you prefer a taxi, airport limo, or top-notch airport transportation service.
Discover Niagara’s beauty with Cabs Niagara Falls Ontario. Reliable Niagara Falls Taxi and Niagara Taxi services for your convenience. Your partner in seamless transportation throughout the Niagara Falls, Ontario region.
Make your journey exceptional with Deerhurst airport limo. We provide top-notch Deerhurst airport luxury transportation, dependable Deerhurst airport taxi, and efficient Deerhurst airport Shuttle services for your travel needs.
Experience convenience with our Charter Bus Services in Chicago. From group tours to corporate events, we offer spacious coaches and professional drivers for your comfort. Trust us for reliable and efficient transportation solutions in Chicago.
GMIFHmvhWQj
What a refreshing take on this subject. I completely agree with The points!
You’ve opened my eyes to new perspectives. Thank you for the enlightenment!
You’ve done a fantastic job of breaking down this topic, like unlocking a door to a secret garden. Intrigued to explore more.
A masterpiece of writing! You’ve covered all bases with elegance.
The article was a delightful read. It’s clear you’re passionate about what you do, and it shows.
A masterpiece of writing—you’ve covered all bases with such finesse, I’m left wanting an encore.
The perspective is incredibly valuable to me. Thanks for opening my eyes to new ideas.
Handling topics with grace and authority, like a professor, but without the monotone lectures.
Brilliant piece of writing. It’s like you’re showing off, but I’m not even mad.
Book Minneapolis airport car service for premium MSP airport transportation. Our options include Minneapolis airport limo service, shuttle, taxi, sedan, black car, SUV, and executive services. Experience comfort and reliability with our private car service Minneapolis.
Travel in style with our airport limo service in Parry Sound. We offer comprehensive taxi service, airport transportation, Parry Sound limo service, reliable taxi, and convenient airport shuttle options.