简体   繁体   中英

Spring MockMVC how to mock @RequestParam Date type

I have a code to test as follows:

@RequestMapping(value = "/prepareLic", method = {RequestMethod.GET})
    public @ResponseBody
    String prepareLice(HttpServletRequest request, @RequestParam String test1, @RequestParam String test2, @RequestParam String test3, @RequestParam String test4, @RequestParam Date liPrintDate, @RequestParam String test5, @RequestParam String test6, @RequestParam String test7) throws NSException, SQLException, ParseException {
      ...
        return new Gson().toJson(jsonResponse);
    }

Unit test define below:

   mockMvc.perform(get("/prepareLic").param("test1", "12").param("test2" ,"cpomName").param("test3", "123").param("test4", "signeeName").
            param("liPrintDate", "22/09/2015").param("test5", "12").param("test6", "O2").param("test7", "12")).andDo(print())
            .andExpect(status().isOk()
            );

When I execute the above unit test the following error is displayed:

      Running com.ApControllerTest
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.

MockHttpServletRequest:
         HTTP Method = GET
         Request URI = /prepareLice
          Parameters = {test1=[test1], test2=[test2], test3=[test3], test4=[test4], liPrintDate =[22/09/2015], test6=[test6], test7=[test7], test8=[test8]}
             Headers = {}

             Handler:
                Type =com.ApController
              Method = public java.lang.Stringcom.ApController.prepareLice(javax.servlet.http.HttpServletRequest,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.util.Date,java.lang.String,java.lang.String,java.lang.String) throws com.dummy.util.NSException,java.sql.SQLException,java.text.ParseException

  Resolved Exception:
                Type = org.springframework.beans.TypeMismatchException

        ModelAndView:
           View name = null
                View = null
               Model = null

            FlashMap:

MockHttpServletResponse:
              Status = 400
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 6.056 sec <<< FAILURE! - in com.ApControllerTest
prepareLiceTest(com.ApControllerTest)  Time elapsed: 2.406 sec  <<< FAILURE!
java.lang.AssertionError: Status expected:<200> but was:<400>
    at com.ApControllerTest.prepareLiceTest(ApControllerTest.java:1606)


Results :

Failed tests: 
  ApControllerTest.prepareLiceTest:1606 Status expected:<200> but was:<400>

Tests run: 1, Failures: 1, Errors: 0, Skipped: 0

------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------

The exception is triggered because liPrintDate is a date object but in the above test it is defined as a String.

Please find import below:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.Principal;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import java.util.logging.Level;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import org.apache.commons.collections.FactoryUtils;
import org.apache.commons.collections.list.LazyList;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.util.IOUtils;
import org.owasp.esapi.ESAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.context.MessageSource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

How can I define liPrintDate as Date in the above unit test since .param takes only String ?

Thanks in advance for any advice.

Try defining the date format for the RequestParam

@RequestMapping(value = "/prepareLic", method = {RequestMethod.GET})
    public @ResponseBody
    String prepareLice(HttpServletRequest request, @RequestParam String test1, 
    @RequestParam String test2, @RequestParam String test3, @RequestParam String test4, 
    @RequestParam @DateTimeFormat(pattern="dd/MM/yyyy") Date liPrintDate, 
    @RequestParam String test5, @RequestParam String test6, @RequestParam String test7) 
        throws NSException, SQLException, ParseException {
      ...
        return new Gson().toJson(jsonResponse);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM