I am beyond frustrated because I can't figure this out. I've been over quite a lot of articles but i can't figure out how to solve this problem, and yet i think i overlook something very simple.
I have a class with a couple of endpoints, one of them is:
@GET
@Path("courses")
@Produces(MediaType.APPLICATION_JSON)
public Response courses(@QueryParam("token") String token) {
Integer studentId = iStudentDAO.getStudentIdByToken(token);
if(studentId == null){
return Response.status(403).build();
} else {
GetStudentsResponse studentCourses = iStudentDAO.getStudentCourses(studentId);
return Response.status(200).entity(courses.name).build();
}
}
This method should always return a Response.status. And thats exactly what i want to test. I know its not possible to unit tests the actual response (200 or 403) but i would like to know how to test if at least Response.status is returned. Im using Mockito for this in my Maven project.
@Test
public void testGetAllCourses () {
String token = "100-200-300";
StudentRequests studentRequests = mock(StudentRequests.class);
when(studentRequests.courses(token)).thenReturn(Response.class);
Response expected = Response.class;
assertEquals(expected, studentRequests.courses());
}
Could anyone explain me how to accomplish this? :)
You should be able to test your specific responses.
Assuming, the method courses
is in a class Controller
. And this is your class under test, your target should be to test the code here, which is the code that you have written in your controller.
Here is an example:
package test;
import static org.junit.Assert.*;
import org.apache.catalina.connector.Response;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
public class ControllerTest {
@Mock
IStudentDAO iStudentDAO;
@InjectMocks
Controller controller;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCoursesWhenStudentIDNotFound() {
Mockito.when(iStudentDAO.getStudentIdByToken("1234")).thenReturn(null);
Response response = controller.courses("1234");
assertEquals(403, response.getStatus())
}
}
Similarly, in the next test case, you can mock the IStudentDAO
, to return a studentId
and then courses for this studentId
and validate that you do get them in the response.