JUnit Testing for Spring MVC Controller

Hello

I have an application that is setup in Spring MVC and I would like to know of a format for testing the controllers.

We are writing jUnit tests for the controller methods, but the only way I know how to access them is from the User Interface (the javascript/Jquery layer to be specific)

I am not seeing how I can involve the User Interface in the Unit tests.

I would like to see an example of a format that I could follow.
onaled777Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gurpsbassiCommented:
Have a look at .Spring MVC Test Framework.

There's also a video I watched a while ago that covers the subject and talks about using HtmlUnit.
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Can you provide one/some examples of your actual controller methods? That would help in pointing you in the right direction.
onaled777Author Commented:
Hello
Thank you for the excellent documentation.
The challenge I am having however is that this is Spring 3.1 and most of the documentation I am finding is Spring 3.2.
I cannot provide method details but this is the signature of one method in the controller that is to be tested

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(method = RequestMethod.POST, value="/getCatList.htm")
	public ModelAndView getOrderCatList(HttpServletRequest request,HttpServletResponse response) throws Exception {

Open in new window


I am focused on testing that.
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

onaled777Author Commented:
this is my attempt thus far:

package com.chenmed.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Test;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;

import com.chenmed.web.constants.EMRConstants;

import static org.junit.Assert.*;
import static org.springframework.test.web.ModelAndViewAssert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"file:src/main/resources/applicationContext-mvc.xml"})

public class PatOrdersControllerTest {

    @Autowired
    private ApplicationContext applicationContext;
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;
    private HandlerAdapter handlerAdapter;
    private PatOrdersController controller;

    @Before
    public void setUp() {
       request = new MockHttpServletRequest();
       response = new MockHttpServletResponse();
       controller = new PatOrdersController();
    }

    @Test
    public void testGetOrderCategoryList() throws Exception {
    	//http://stackoverflow.com/questions/5774349/how-to-unit-test-a-spring-mvc-annotated-controller
        request.setMethod("POST");
        request.setRequestURI("/getCategoryList.htm");
        request.addParameter("catType", "LAB");
        ModelAndView mav= controller.getOrderCategoryList(request,response);
        assertEquals("ordertypes", mav.getViewName());        
    }
}

Open in new window



The challenge I am having is that I then meet up on the security for the controller in this line and it fails because no one is really logged in:
			UserVO userDetailsVO =  (UserVO)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			Integer practiceId = userDetailsVO.getPracticeCtx().getPracticeId();

Open in new window


How do I work around that?
mccarlIT Business Systems Analyst / Software DeveloperCommented:
I'm typing this from a mobile so it's a bit hard to give much detail but TestingAutheticationToken should be able to help you out. Add a line like the below to the appropriate place in your test...

SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(userDetailsVO, null));

With an appropriately configured userDetailsVO object to simulate a logged in user.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
onaled777Author Commented:
That worked!  Thank you!
mccarlIT Business Systems Analyst / Software DeveloperCommented:
You're welcome!!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.