Samples of jUnit tests for old project

junitmeme
Today I wanna show some of the cases when Unit tests helped me do refactoring and keep eyes on codebase changes by programmers who works remotely.
One day I received a task to create endpoint which allows adding new defect object – basically, show JSP page where located form with some parameters and inputs (We will not check form submit test in this post). Parent object of each defect is Checklist, the server receives it as parameter “qcChecklistId”. This Project using Struts MVC, Spring, Hibernate (but it’s not important in this case).
What will I test?
  1. If endpoint/method exists.
  2. If a method receives “qcChecklistId” parameter and validates it.
  3. If a method put Checklist object into request attributes returns “addNewDefect”.
  4. If a method returns null and status code 404 in the case of not valid data.
So let’s start
You can check method code here, it helps understand logic of test class:
public String addNewDefect() {
String qcChecklistId = getServletRequest().getParameter(“qcChecklistId”);
if (qcChecklistId != null && !qcChecklistId.isEmpty()) {
Productqualitycontrol qcChecklist = this.productQualityControlSer.findById(qcChecklistId);
if (qcChecklist != null) {
getServletRequest().setAttribute(“qcChecklist”, qcChecklist);
return “addNewDefect”;
}
}
try {
this.getServletResponse().sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
For the beginning I’ll define which runner to use:
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class QCCheckListActionTest {
….
Then define objects which in use and mocks:
QCCheckListAction action;
MockHttpServletResponse response;
MockHttpServletRequest request;
MockServletContext context;
@Mock ProductQualityControlSer productQualityControlSer;
private final static String QC_CHECK_LIST_ID = “qcChecklistId”;
private final static String ADD_NEW_REQUEST = “addNewDefect”;
private final static String QC_CHECK_LIST_OBJECT = “qcChecklist”;
Please keep attention on:
MockHttpServletResponse response;
MockHttpServletRequest request;
MockServletContext context;
Those classes come from org.springframework.mock.web and helps you deal with Serlet service objects – mock them in very convenient way.
Setup starting configuration before each test:
@Before
public void init() {
context = new MockServletContext();
response = new MockHttpServletResponse();
request = new MockHttpServletRequest(“GET”, “addNewDefectQCCheckList.action”);
action = new QCCheckListAction();
action.setServletContext(context);
action.setServletResponse(response);
action.setServletRequest(request);
when(productQualityControlSer.findById(anyString()))
.thenReturn(null);
when(productQualityControlSer.findById(“1”))
.thenReturn(mock(Productqualitycontrol.class));
action.setProductQualityControlSer(productQualityControlSer);
}
Implement tests
If endpoint/method exists.
@Test
public void checkIfMethodExist() {
request.addParameter(QC_CHECK_LIST_ID, “1”);
assertNotNull(action.addNewDefect());
verify(productQualityControlSer, atLeastOnce()).findById(“1”);
}
If method receives “qcChecklistId” parameter and validates it.
@Test
public void checkIfNoParametersReturnError() {
// When empty parameters
request.removeAllParameters();
assertNull(“Should return null”, action.addNewDefect());
assertEquals(HttpServletResponse.SC_NOT_FOUND, action.getServletResponse().getStatus());
}
If method put Checklist object into request attributes and method returns “addNewDefect”.
@Test
public void checkIfObjectAddedToResponse() {
request.addParameter(QC_CHECK_LIST_ID, “1”);
assertEquals(ADD_NEW_REQUEST, action.addNewDefect());
assertNotNull(“System should set qcchecklist object to request attribute.”, request.getAttribute(QC_CHECK_LIST_OBJECT));
}
If the method returns null and status code 404 in the case of not valid data.
@Test
public void checkIfNoFindByIdReturnError() {
// When can not find Productqualitycontrol object in DB
request.addParameter(QC_CHECK_LIST_ID, “2”);
assertNull(“Should return null”, action.addNewDefect());
assertEquals(HttpServletResponse.SC_NOT_FOUND, action.getServletResponse().getStatus());
}
What can we get from so small test case? First of all, we always will be informed if someone renamed method, changed return value (this is important for Struts mvc because it uses to return value to check which JSP to provide).
Entire code of test file you can see here:
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import sbe.hibernate.entity.Productqualitycontrol;
import sbe.service.ProductQualityControlSer;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class QCCheckListActionTest {
QCCheckListAction action;
MockHttpServletResponse response;
MockHttpServletRequest request;
MockServletContext context;
@Mock ProductQualityControlSer productQualityControlSer;
private final static String QC_CHECK_LIST_ID = “qcChecklistId”;
private final static String ADD_NEW_REQUEST = “addNewDefect”;
private final static String QC_CHECK_LIST_OBJECT = “qcChecklist”;
@Before
public void init() {
context = new MockServletContext();
response = new MockHttpServletResponse();
request = new MockHttpServletRequest(“GET”, “addNewDefectQCCheckList.action”);
action = new QCCheckListAction();
action.setServletContext(context);
action.setServletResponse(response);
action.setServletRequest(request);
when(productQualityControlSer.findById(anyString()))
.thenReturn(null);
when(productQualityControlSer.findById(“1”))
.thenReturn(mock(Productqualitycontrol.class));
action.setProductQualityControlSer(productQualityControlSer);
}
@Test
public void checkIfMethodExist() {
request.addParameter(QC_CHECK_LIST_ID, “1”);
assertNotNull(action.addNewDefect());
verify(productQualityControlSer, atLeastOnce()).findById(“1”);
}
@Test
public void checkIfNoParametersReturnError() {
// When empty parameters
request.removeAllParameters();
assertNull(“Should return null”, action.addNewDefect());
assertEquals(HttpServletResponse.SC_NOT_FOUND, action.getServletResponse().getStatus());
}
@Test
public void checkIfNoFindByIdReturnError() {
// When can not find Productqualitycontrol object in DB
request.addParameter(QC_CHECK_LIST_ID, “2”);
assertNull(“Should return null”, action.addNewDefect());
assertEquals(HttpServletResponse.SC_NOT_FOUND, action.getServletResponse().getStatus());
}
@Test
public void checkIfObjectAddedToResponse() {
request.addParameter(QC_CHECK_LIST_ID, “1”);
assertEquals(ADD_NEW_REQUEST, action.addNewDefect());
assertNotNull(“System should set qcchecklist object to request attribute.”, request.getAttribute(QC_CHECK_LIST_OBJECT));
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s