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));
}
}
Connect effortlessly between Buffalo and Oakville with our premier Airport Limo and Taxi Transportation. Whether it’s a lavish limo or a convenient taxi, we provide reliable services tailored to your needs. Experience comfort and convenience on your journey from Buffalo to Oakville.
Simplify your airport transportation with our O’Hare Airport Pickup/Drop Service. From shuttle buses to private transfers, we cater to diverse preferences. Experience seamless travel from O’Hare to downtown and beyond, ensuring a stress-free journey.
The ability to present nuanced ideas so clearly is something I truly respect.
The post added a new layer to my understanding of the subject. Thanks for sharing The knowledge.
The unique perspective on this subject was enlightening. It’s refreshing to see someone so passionate about their topic.
This post has been incredibly helpful, like a guiding hand in a crowded room. The guidance is much appreciated.
This post was a breath of fresh air. Thank you for The unique insights!
Consistently high-high quality content, as if you’re trying to show us all up.
The post has broadened my perspective in ways I didn’t expect. Thank you for that.
The approach to topics is like a master painter’s to a canvas, with each stroke adding depth and perspective.
The insights are like a fine wine—rich, fulfilling, and leaving me wanting more.
This is a brilliant piece of writing. You’ve nailed it perfectly!
The grace and authority with which you handle topics are awe-inspiring. I always come away with new knowledge.
You have a gift for explaining things in an understandable way, much like a smooth talker who knows just what to say.
Reading The post was like going on a first date with my mind. Excited for the next rendezvous.
You’ve done a fantastic job of breaking down this topic, like unlocking a door to a secret garden. Intrigued to explore more.
A constant source of inspiration and knowledge, like a muse but less mythical.
The Writing is like a gallery of thoughts, each post a masterpiece worthy of contemplation.
You write with such passion and clarity, it’s like listening to a love song for the mind.
The post was a beacon of knowledge, lighting up my day as if you knew just what I needed to hear.
I appreciate how you’ve explained things so clearly. It really helped me understand the topic better.
The unique perspective on this subject was enlightening. It’s refreshing to see someone so passionate about their topic.
The writing style is like a signature scent—distinct, memorable, and always pleasant.
Thank you for consistently producing such high-high quality content.
Thank you for adding value to the conversation with The insights.
The insights light up my intellect like fireworks. Thanks for the show!
Beautifully written and informative, making the rest of the internet look bad.
You’ve opened my eyes to new perspectives. Thank you for the enlightenment!
The creativity and intelligence shine through, blinding almost, but I’ll keep my sunglasses handy.
The post was a beacon of knowledge. Thanks for casting light on this subject for me.
Refreshing take on the subject, like a cold splash of water to my long-held beliefs.
Amazed by The knowledge breadth, or what I’ve been mistaking for just good Googling skills.
I admire the way you tackled this hard to understand issue. Very enlightening!
Reading The work is like catching up with an old friend; comfortable, enlightening, and always welcome.
Beautifully written and incredibly informative, The post has captured my attention as if it were a love letter written just for me.
Discovering The Writing felt like finding the perfect match. The intellect and charm are a rare combo.
I appreciate the balance and fairness in The writing, like a perfect partner who always keeps things interesting. Great job!
Delightful read. The passion is visible, or at least, very well faked.
Bookmarking this for future reference, but also because The advice is as invaluable as The attention.
I’m amazed by the depth and breadth of The knowledge. Thanks for sharing!
Thank you for the hard work you put into this post. It’s much appreciated!
Stumbling upon The article was a highlight of my day. It was just what I needed to read.
I learned a lot, and now I’m curious about what else you could teach me. The intelligence is as captivating as The prose.
I’m officially a fan of The work. It’s like having a crush, but intellectually stimulating.
Most comprehensive article on this topic. I guess internet rabbit holes do pay off.
Every piece you write is like adding another book to my mental library. Thanks for expanding my collection.
Amazed by The knowledge breadth, or what I’ve been mistaking for just good Googling skills.
Reading The post was like going on a first date with my mind. Excited for the next rendezvous.
The blend of informative and entertaining content is perfect. I enjoyed every word.
A masterpiece of writing. Van Gogh’s got nothing on you, except maybe both ears.