Announcement Announcement Module
Collapse
No announcement yet.
How To Test Controller(MVC) via EasyMock And JUnit? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How To Test Controller(MVC) via EasyMock And JUnit?

    Hi Everyone,

    How To Test Controller(MVC) via EasyMock And JUnit?

    Here is my code

    Code:
    @Controller
    public class AdminFr extends AdminController {
    
    	@Autowired
    	FrUserService frUserService;
    	@Autowired
    	ClientUserService clientUserService;
    	@Autowired
    	DateStoreService dateStoreService;
    	
    	@Autowired
    	ConfigService configService;
    	@Autowired
    	StatService statService;
    
    @RequestMapping("/adminPhoneNumberCountByProvince/")
    public void getPhoneNumberByProvince(@RequestParam(required = false)
    	Integer start, @RequestParam(required = false)
    	Integer limit, HttpServletResponse response, Integer year, Integer month) {
    		Calendar ca = Calendar.getInstance();
    		Date currentDate = null;
    		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
    		if (start == null) {
    			start = 0;
    		}
    		if (limit == null) {
    			limit = 30;
    		}
    		if (year == null) {
    			year = ca.get(Calendar.YEAR);
    		}
    		if (month == null) {
    			ca.add(Calendar.MONTH, 1);
    			month = ca.get(Calendar.MONTH);
    		}
    		String currentTime = Tools.getString(year, "-", month);
    		try {
    			currentDate = format.parse(currentTime);
    		} catch (ParseException e) {
    			logger.error("Date format fail", e);
    		}
    		List list = new ArrayList();
    		List ls = clientUserService.getPhoneNumberCountByProvince(currentDate,
    				start, limit);
    		if (ls != null && !ls.isEmpty()) {
    			for (int i = 0; i < ls.size(); i++) {
    				Map beanMap = new HashMap();
    				Object[] object = (Object[]) ls.get(i);
    				if (object[0] != null && !object[0].toString().equals("")) {
    					beanMap.put("province", object[0]);
    					beanMap.put("count", object[1]);
    					list.add(beanMap);
    				}
    			}
    		}
    		JSONMap map = new JSONMap();
    		map.put("totalProperty", 2000);
    		map.put("list", list);
    		map.flush(response);
    }
    }

    how can i test this method?



    thanks in advance.

  • #2
    Spring has really good mock classes with you can test the controllers. In tests you can create mock objects for HttpServletRequest, HttpServletResponse and for HttpSession if needed.

    You can find several articles by googling it around. Here's the one I found from my bookmars.
    http://www.devx.com/Java/Article/30067/1954

    Comment


    • #3
      i don't know how to set the parameter and how to got the

      JSONMap map = new JSONMap();
      map.put("totalProperty", 2000);
      map.put("list", list);
      map.flush(response);


      and to write Assert condition to validate it

      Comment


      • #4
        1. Create an instance of your class
        2. Call the method (with a MockHttpServletResponse or a EasyMock with some recordings)
        3. assert what you want.

        However I have some questions about your class

        1. The year/month don't appear to be mapped to a requestparam so where do they come from?
        2. Why don't you put the conversion logic in some other class (i.e. a PropertyEditor) that way it is reusable
        3. Your Controller is now tied to a particulair view technology, instead of creating a JSonMap in your Controller consider creating a JSonView which converts the model into a JSON string. That way your controller/view are decoupled.
        4. Working with Calendars and Date is really ***** consider something like JodaTime for working with dates.

        Comment


        • #5
          Marten Deinum
          Thanks a lot ,'m using ExtJs/Wap As View layout,

          my boss let me to write the controller test via Mock and JUnit,but i dont know how to

          set the request to that kind of controller ,and don't know how to get the response/result

          to test it(cause its my first to use Mock and JUnit)

          many thanks

          Comment


          • #6
            Code:
            @Test
            public void someTestMethod() {
              MockHttpServletResponse response = new MockHttpServletResponse();
            
              yourcontroller.getPhoneNumberByProvince(null, null, response, null, null); //Or what ever params you like
            
              assertSomeThing(response.getContentAsString(), ...);
            
            }
            SOmething like this, next to that I really suggest you re-read my suggestions and first understand what I'm pointing out. Also read the MVC chapter on the reference guide.

            Comment


            • #7
              Dear Marten Deinum
              ,Thanks for your reply,and i 'm really thanks for your advice~! ^_^

              I have got green in junit ,thanks a lot

              @RunWith(SpringJUnit4ClassRunner.class)
              @ContextConfiguration(locations = {"file:/web/WEB-INF/classes/spring/dispatch-servlet.xml"
              })
              public class AdminFrTest {
              @Autowired
              SomeControllerClass someControllerClass ;
              @Test
              public void testGetPhoneNumberByProvinceIntegerIntegerHttpServ letResponseIntegerInteger() {
              MockHttpServletResponse response = new MockHttpServletResponse();
              someControllerClass .getPhoneNumberByProvince(1, 1, response, 2008, 9);
              try {
              Assert.assertNotNull(response.getContentAsString() );
              } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
              }
              }

              }

              Comment

              Working...
              X