Pietro
Pietro

Reputation: 1835

Spring MVC 4: Mockmvc empty MockResponse content

I'm getting started using Spring.

Following this tutorial when I reach WebDomainIntegrationTest the test fails because of an empty content response.

I'm thinking maybe that the problem could be the serverport. The application runs on port 8000 and the integration test ask for localhost port 80. (if this is the problem, how can I set a different port?)

CODE

SiteController:

@Controller
@RequestMapping("/")
public class SiteController {

    private static final Logger LOG = LoggerFactory.getLogger(SiteController.class);

    @Autowired
    private MenuService menuService;

    @Autowired
    private Basket basket;

    @RequestMapping(method = RequestMethod.GET)
    public String getCurrentMenu(Model model) {
        LOG.debug("Yummy MenuItemDetails to home view");
        model.addAttribute("menuItems",getMenuItems(menuService.requestAllMenuItems(new RequestAllMenuItemsEvent())));
        System.out.println("getCurrentMenu");
        return "home";
    }

    private List<MenuItem> getMenuItems(AllMenuItemsEvent requestAllMenuItems) {
        List<MenuItem> menuDetails = new ArrayList<MenuItem>();

        for (MenuItemDetails menuItemDetails : requestAllMenuItems.getMenuItemDetails()) {
            menuDetails.add(MenuItem.fromMenuDetails(menuItemDetails));
        }

        return menuDetails;
    }


    /*
    Lastly, you need to put the Basket into the model for the view to be able to read from.
    This method takes the auto injected Basket and annotates it so that it is automatically merged into the Model.
     */
    @ModelAttribute("basket")
    private Basket getBasket() {

        return basket;
    }

}

WebDomainIntegrationTest:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { PersistenceConfig.class, CoreConfig.class, WebConfig.class })
public class WebDomainIntegrationTest {
    private static final String STANDARD = "Yummy Noodles";
    private static final String CHEF_SPECIAL = "Special Yummy Noodles";
    private static final String LOW_CAL = "Low cal Yummy Noodles";

    private MockMvc mockMvc;

    @Autowired
    WebApplicationContext webApplicationContext;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void thatTextReturned() throws Exception {
        mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andDo(print())
                .andExpect(content().string(containsString(STANDARD)))
                .andExpect(content().string(containsString(CHEF_SPECIAL)))
                .andExpect(content().string(containsString(LOW_CAL)));
    }

}

Home view:

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>

<tiles:insertDefinition name="defaultTemplate">
    <tiles:putAttribute name="body">
        <div class="body">
            <h1>Home page !</h1>

            <div class="col-md-12 text-center">
                <c:forEach var="item" items="${menuItems}">
                    <div class="name"><c:out value="${item.name}"/></div>
                </c:forEach>
            </div>
        </div>
    </tiles:putAttribute>
</tiles:insertDefinition>

Test on model attributes (successful!)

@ContextConfiguration(classes = {PersistenceConfig.class, CoreConfig.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class CoreDomainIntegrationTest {

    @Autowired
    MenuService menuService;

    @Autowired
    OrderService orderService;

    @Test
    public void thatAllMenuItemsReturned() {

        AllMenuItemsEvent allMenuItems = menuService.requestAllMenuItems(new RequestAllMenuItemsEvent());

        assertEquals(3, allMenuItems.getMenuItemDetails().size());

    }

    @Test
    public void addANewOrderToTheSystem() {

        CreateOrderEvent ev = new CreateOrderEvent(new OrderDetails());

        orderService.createOrder(ev);

        AllOrdersEvent allOrders = orderService.requestAllOrders(new RequestAllOrdersEvent());

        assertEquals(1, allOrders.getOrdersDetails().size());
    }

}

Upvotes: 3

Views: 4441

Answers (2)

Jaiwo99
Jaiwo99

Reputation: 10017

The problem is, if you are using jsp related technique, you cannot use content(), you need to use model(), try this:

    @Test
    public void thatTextReturned() throws Exception {
        mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andDo(print())
                .andExpect(model().attribute("test", hasItem(hasProperty("name", value)))));
    }

The Matcher I'm using is from Hamcrest.

Upvotes: 5

xianlinbox
xianlinbox

Reputation: 979

  1. Spring Integration test is based on Spring Container, It doesn't care which port or host you are running your application.

  2. For your problem , the issue is on this part of code:

    @RequestMapping(method = RequestMethod.GET)
    public String getCurrentMenu(Model model) {
        LOG.debug("Yummy MenuItemDetails to home view");
        model.addAttribute("menuItems",getMenuItems(menuService.requestAllMenuItems(new RequestAllMenuItemsEvent())));
        System.out.println("getCurrentMenu");
        return "home";
    }
    

the model didn't attach to your response. please check home page ,does it generate the model attribute 'menuItems'?

Upvotes: 0

Related Questions