I use Mockito with Junit to test the application, I need to add headers to the HttpServletRequest while mocking. This is the first time I use a mock concept to test an application. How can we set headers for an object request using this mock concept?
Java Code:
@Produces({ MediaType.APPLICATION_JSON }) @Path("/devices") public class DvrRestService { private static final Logger logger = LoggerFactory.getLogger(DvrRestService.class); private DvrMiddleService dvrMiddleService; @Inject public DvrRestService(DvrMiddleService dvrMiddleService) { this.dvrMiddleService = dvrMiddleService; } @GET @Path("/{deviceId}/metadata") public Response getDeviceMetadata(@Context HttpServletRequest request, @PathParam("deviceId") String deviceId, @RequiredSession final Session session) { try { public static String[] REQUEST_HEADERS = { "if-none-match" }; List<String> requiredHeaders = Lists.newArrayList(REQUEST_HEADERS); Map<String, String> headers = new HashMap<String, String>(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) {
Here is my test code:
public class DvrRestServiceTest { static DvrMiddleService dms; static HttpServletRequest request; static Session session; static DvrRestService drs; public static final String DeviceId = "000004D42070"; @BeforeClass public static void init(){ dms = mock(DvrMiddleService.class); request = mock(HttpServletRequest.class); session = mock(Session.class); drs = new DvrRestService(dms); } @Test public void getDeviceMetadataTest(){ Response rs = drs.getDeviceMetadata(request, DeviceId, session); assertEquals(Response.Status.OK, rs.getStatus()); } }
source share