Reputation: 5267
I need to pass in a non-null HttpServletRequest somehow or control HelperClass.getUser(request) which is throwing an error(the method does request.getHeader() inside and as the request is null it throws an error and fails the test).
We would like to unit test our REST API, so we quickly know if a change (or a developer) breaks it or if we have a bug etc. eventually to start doing TDD/BDD. These tests are destined eventually for use for automated builds by ant. I can call REST API and set headers from java but don't think this would be a unit test? Would depend on running it on local host? Could be wrong about that
Code:
@Path("service/")
public class Service {
static DataAccess da = null;
@javax.ws.rs.core.Context HttpServletRequest request;
//constructor where doa will be mock object
public Service(DataAccess dao){
da = dao;
}
@GET
@Path("custom-object/{date}/{batch}")
@Produces({"application/xml", "application/json", "application/x-protobuf"})
//Method to test
public CustomObject getCustomObject(
@PathParam("date") String date,
@PathParam("batch") int batch,
@QueryParam("type") String type) {
String user = HelperClass.getUser(request); // this is causing me issues
//da will be a mock object
CustomObject returnedVal = da(user,DatatypeConverter.parseDateTime(date).getTime(), batch, artifactType);
return returnedVal;
}
}
Test using junit/mockito (happy to use powermock as a solution) :
@Test
public void testGetCustomObject() {
System.out.println("getCustomObject");
//Arrange
DataAccess da = mock(DataAccess.class);
Service instance = new Service(da);
String date = "2010-04-05T17:16:00Z";
int batch = 0;
String type = "";
CustomObject expResult = null;
//Act
CustomObject result = instance.getCustomObject(date, batch, type);
//Assert
assertEquals(expResult, result);
}
The test passes if I hardcode the String user="123";
. I need to get over this problem before writing useful tests. Can anyone give example code to mock/control this line of code to effectively set user
as a non-null string (this line String user = HelperClass.getUser(request);
is in EVERY API method)
Upvotes: 0
Views: 4318
Reputation: 7947
You could try the REST assured library to help unit test REST services.
Upvotes: 2
Reputation: 389
For constructing HttpServletRequest you could use some mock object like Spring's MockHttpServletRequest.
Or you could refactor your helper class and make the getUser() method non-static and use Mockito to mock it in your unit tests.
Upvotes: 0