Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

In a previous blog, I talked about Testing Springframework MVC Rest controllers with MockMVC. What I didn’t know is that you can use the MockMVC framework to also interrogate the Request object.

In this case, we have an Interceptor that is modifying the request by modifying an object’s property and adding that object to the request as a request attribute. To test this, we had to be able to see the value of the request attribute object after the request is done. Luckily MockMVC provides us the ability to do just that.

To accomplish this, I had to utilize the RequestResultMatchers via MockMvcResultMatchers.request() method to get a reference to the request object. Once I had the request object, I was able to get the object being stored as a request attribute by calling the attribute() method . Once I had the object, I was able to access it’s properties by calling hasProperty on it. From there on, I was able to use matchers that I was used to using.

    @Test
    public void testExtractStateFromCookie() {

        try {
            mockMvc.perform(get("/legacy/tote/currentrace")
                                .param("param1", "value1")
                                .param("param2", "value2")
                                .param("param3", "value3")
                                .cookie(new Cookie("STATE", "kY")))
                   .andExpect(request().attribute("USER_INFO", hasProperty("state", equalToIgnoringCase("ky"))));
        } catch (Exception e) {
            fail(e.toString());
        }
    }

Along the way, I did use some new Matchers. They are:

  • org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase() – This provides functionality similar to is(), but ignores the case of the text.
  • org.hamcrest.core.IsNull.nullValue – This allows for easy comparison to null
  • IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace() – All leading and trailing whitespace is ignored. Any duplicate white spaces within the string are considered single spaces.
  • IsEmptyString.isEmptyOrNullString() – compares against empty string or null (e.g. StringUtils.isBlank()).

August 15th, 2017

Posted In: hamcrest, MockMVC

Leave a Comment

Have you ever had the case where you had to test for the negative of something? I was helping a teammate who wanted to test that a collection was not empty. It was pretty hard to track down how to test for that.

We settled on not()

import static org.hamcrest.Matchers.not;
...
...not(hasSize(0))

This was pretty hard to find. There wasn’t much documentation on negation.

June 30th, 2014

Posted In: hamcrest, Java, JUnit

Leave a Comment

LinkedIn Auto Publish Powered By : XYZScripts.com