waffel’s Weblog

Februar 27, 2013

testing REST interface with Spring 3.2 and a session scoped bean

Einsortiert unter: java,spring — Thomas Wabner @ 8:00 nachmittags
Tags: , , , , , , , , ,

There are some nice articles around the “spring 3.2 testing capabilities” like the spring documentation itself, this blog and this blog.

I wanted to not only test one request/response action against my REST interface. I wanted to simulate and test more of a conversation as it typical happens in the UI.

Following REST interface I wanted to create and test:

@RequestMapping("/customer")
public interface RESTCustomer {

@RequestMapping(
method = RequestMethod.POST)
@ResponseBody
Customer create(@RequestParam("firstname") final String firstname,
@RequestParam("lastname") final String lastname);

@RequestMapping(
method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
void delete(@RequestParam("id") final String... customerIds);

@RequestMapping(
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
@ResponseBody
Collection<Customer> getAll();

@RequestMapping(
value = "/update",
method = RequestMethod.POST)
@ResponseBody
Customer update(@RequestParam("id") final String id, @RequestParam("firstname") final String firstname);

}

Following test steps I had in mind, to test the create method:

  1. Get a list of all customers and remember the count
  2. Create a new customer
  3. Check, that the ID of the returning Customer was updated
  4. Get again a list of all customers
  5. Check the size of the customer list before and after creation … they should differ between one entry/li>

The new Spring Framework version 3.2 introduced some nice feature to do REST testing with minimal effort.

To test such conversion, you need beside the WebApplicationContext a MockHttpSession which has to be used between different mockMvc calls, on one test case.

The following base test structure is required:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(
  classes = {
    MyConfig.class,
  })
public class RESTCustomerTest {
  
@Autowired
  private WebApplicationContext wac;

  @Autowired
  MockHttpSession session;

  MockMvc mockMvc;

  ObjectMapper jsonObjectMapper;

  @Before
  public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    jsonObjectMapper = new ObjectMapper();
  }

  @Test
  public void testCreate() throws Exception {
    ....
  }
}

Let assume, there is an implementation of the RESTCustomer service interface like this:


@Component
public class CustomerResource implements RESTCustomer {

  private final PlatformService service;

  @Autowired
  public CustomerResource(final PlatformService service) {
    this.service = service;
  }

  @Override
  public Customer create(final String firstname, final String lastname) {
    ...
    return service.createCustomer(firstname, lastname);
  }

  @Override
  public Collection<Customer> getAll() {
    ...
    return service.getAllCustomers();
  }

}

Assume also, that the autowired PlatformService is a Session scoped bean (somewhere configured inside the spring configuration).

Now our testing method can be like this:


  int countCustomers() throws Exception {
    final MvcResult mvcResult = mockMvc.perform(get("/customer").session(session).accept(MediaType.APPLICATION_JSON))
        .andReturn();
    final Collection<Customer> customers = getRawObjects(mvcResult);
    return customers.size();
  }

Collection<Customer> getRawObjects(final MvcResult mvcResult) throws Exception {
    return jsonObjectMapper.readValue(mvcResult.getResponse().getContentAsString(),
        new TypeReference<Collection<Customer>() {
        });
  }

Customer getRawObject(final MvcResult mvcResult) throws Exception {
    return jsonObjectMapper.readValue(mvcResult.getResponse().getContentAsString(),
        new TypeReference<Customer>() {
        });
  }

  @Test
  public void testCreate() throws Exception {
    // get default customer list and count
    final int originalCustomerSize = countCustomers();

    // create new customer
    final MvcResult mvcResult = mockMvc
        .perform(
            post("/customer/?firstname={firstname}&lastname={lastname}","testFirstname", "testLastName").session(session).accept(
                MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andReturn();
    final Customer customerObject = getRawObject(mvcResult);
    assertNotNull("id of new customer should not empty", customerObject.get("id"));
    assertEquals("newly firstname should match", "testFirstname", customerObject.get("firstname");

    // again get list of all customers and check, if one more is available
    assertEquals("after new customer was created, the size should be one more", originalCustomerSize + 1, countCustomers());
  }

To get such conversation to work, you need to pass the session with .session(session) between the mockMvc calls. Else, every new mockMvc call creates a new session and your test fail.

REMEMBER: The trick is to pass the autowired MockHttpSession between the mock MVC requests.

April 27, 2009

How to test spring session or request scope beans

Einsortiert unter: spring — Thomas Wabner @ 1:45 nachmittags
Tags: , , , , , , , ,

Update Newer Spring Framework versions (I guess starting with 3.1) have better support and a better solution for this problem.

Often you need test cases where you want to use spring configured beans from a existing spring configuration instead of writing mock objects.

In such cases you can use the spring ContextConfiguration class annotation to load your spring configurations. For test cases you may also extend the AbstractTestNGSpringContextTests which gives you nice test support facilities.

But how to test beans which using special scopes like session or request?

The AbstractTestNGSpringContextTests does not provide support to test scoped beans.

Our test module provides a SimpleMapScope implementation, which can be used for scoped beans. There is also a spring configuration for the scopes request and session: session-request-testscopes.xml which can be used as a ContextConfiguration location.

For example you can write follow simple test case:

....

@ContextConfiguration(locations = {"/org/waffel/test/session-request-testscopes.xml", 
  "/org/waffel/my-app-beans.xml})
public class SimpleScopeBeansTest extends AbstractTestNGSpringContextTests {

  /**
   * A bean which is in scope session.
   */
  @Autowired
  @Qualifier("sessionScopedBean")
  private MyBean sessionScopedBean;
  
  @Test
  public void testAccessToBean() {
    AssertNotNull(sessionScopedBean);
  }

....

This test uses the test scope spring configuration and another spring configuration, where the sessionScopedBean is in scope session. With the autowired feature, you have instantly access to the bean. Also if the bean is in session or request scope.

The SimpleMapScope implementation:

package org.waffel.test.spring;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

/**
 * This simple scope implementation uses internal a {@link Map} to hold objects
 * in the scope. This scope implementation can be used for testing beans which
 * wants to be stayed for example in session or request scope.
 * <p>
 * To use this scope in your test cases, simple configure a
 * {@link org.springframework.beans.factory.config.CustomScopeConfigurer} with
 * the required scope name:
 * 
 * <pre>
 * &lt;bean class=&quot;org.springframework.beans.factory.config.CustomScopeConfigurer&quot;&gt;
 *   &lt;property name=&quot;scopes&quot;&gt; 
 *     &lt;map&gt; 
 *       &lt;entry key=&quot;session&quot;&gt; 
 *         &lt;bean class=&quot;org.waffel.spring.SessionScope&quot; /&gt; 
 *       &lt;/entry&gt; 
 *     &lt;/map&gt;
 *   &lt;/property&gt; 
 * &lt;/bean&gt;
 * </pre>
 * 
 * Because the
 * {@link org.springframework.beans.factory.config.CustomScopeConfigurer} is a
 * {@link org.springframework.beans.factory.config.BeanPostProcessor} all
 * requested beans for the scope loaded with that post processor if the
 * registered scope match.
 * </p>
 * 
 * @author waffel
 */
public class SimpleMapScope implements Scope {

  /**
   * This map contains for each bean name or ID the created object. The objects
   * are created with a spring object factory.
   */
  private final Map<string , Object> objectMap = new HashMap</string><string , Object>();

  /**
   * {@inheritDoc}
   */
  public Object get(final String theName, final ObjectFactory theObjectFactory) {
    Object object = objectMap.get(theName);
    if (null == object) {
      object = theObjectFactory.getObject();
      objectMap.put(theName, object);
    }
    return object;
  }

  /**
   * {@inheritDoc}
   */
  public String getConversationId() {
    return null;
  }

  /**
   * {@inheritDoc}
   */
  public void registerDestructionCallback(final String theName, final Runnable theCallback) {
    // nothing to do ... this is optional and not required
  }

  /**
   * {@inheritDoc}
   */
  public Object remove(final String theName) {
    return objectMap.remove(theName);
  }

}

The session-request-testscopes.xml source:

< ?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

  <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
      <map>
        <entry key="session">
          <bean class="org.waffel.test.spring.SimpleMapScope" />
        </entry>
        <entry key="request">
          <bean class="org.waffel.test.spring.SimpleMapScope" />
        </entry>
      </map>
    </property>
  </bean>

</beans>

Another approach can be found in ahöhma’s weblog.

The Rubric Theme. Bloggen Sie auf WordPress.com.

Follow

Erhalte jeden neuen Beitrag in deinen Posteingang.

Schließe dich 27 Followern an