Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JUnit and testing a void method with request.setAttribute

forumKid2May 20 2010 — edited May 20 2010
I know this is a ton of information out there on running unit tests on void methods. The void method here either sets or removes a request attribute. I'm not so sure how to write the correct junit test. I'm currently using mockito.I'm not necessarily looking for someone to whip up code for this. Merely just looking for some advice on how to test it, although if someone has a snippet I would appreciate that too. Im just not sure how to effectively test this method.

Here is my java method that I want to unit test:
	public void checkClientsSession(HttpServletRequest request)
			throws Exception {

		try {

			// Set the site equal to the form parameter
			String site = (String) request.getParameter(MyConstants.SITE);

			// Sets request.getSession to false
			MyUserSession userSession = new MyUserSession();
			HttpSession session = userSession.getSession(request);

			// If the site is null or empty
			if (site == null || "".equals(site)) {

				// Set to the respective session attribute
				site = (String) session.getAttribute(MyConstants.SITE);
			}

			// If the site is client, then remove the session with name
			// "PASSWORD_AUTHENTICATED".
			if (MyConstants.CLIENT.equalsIgnoreCase(site)) {
				String keepUserInSession = request
						.getParameter("keepUserInSession");

				if (StringUtils.isEmpty(keepUserInSession)) {
					request.getSession().removeAttribute(
							MyConstants.PASSWORD_AUTHENTICATED);
				}
			}

		} catch (Exception e) {
			LOG.severe("Session is expired", e);
			e.printStackTrace();
		}
	}
Here is what I have so far for a unit test:
import static org.mockito.Mockito.mock;

import javax.servlet.http.HttpServletRequest;
import static org.mockito.Mockito.when;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class MyActionTest extends MyAction {

	private HttpServletRequest request;

	@Before
	public void setUp() throws Exception {

		request = mock(HttpServletRequest.class);
		when(request.getParameter("site")).thenReturn("site");
	}

	@Test
	public void testCheckClientsSession() throws Exception {
		
		//This is obviously where I need to do more code so that it actually performs a test
		checkClientsSession(request);
	}

	@After
	public void tearDown() throws Exception {
		request = null;
	}

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 17 2010
Added on May 20 2010
4 comments
4,260 views