web-dev-qa-db-fra.com

Comment se moquer de HttpServletRequest avec des en-têtes?

J'utilise Mockito avec Junit pour tester l'application, j'ai besoin d'ajouter des en-têtes à HttpServletRequest pendant la simulation. C'est la première fois que j'utilise un concept simulé pour tester l'application. Comment pouvons-nous définir des en-têtes pour demander un objet tout en utilisant ce concept factice?

Code Java:

@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 gettting NullPointerException

                String headerName = headerNames.nextElement();
                if (requiredHeaders.contains(headerName.toLowerCase())) {
                    String value = request.getHeader(headerName);
                    if (value != null) {
                        headers.put(headerName, value);
                        System.out.println("headerName: " + headerName + ", Value: " + value);
                    }
                }
            }
            DvrResponse response = dvrMiddleService.getDeviceMetadata(deviceId.toUpperCase(), getHeaders(request));
            return processResponse(response.statusCode, response.getResponse(), DeviceMetadataResponse.class,
                response.getHeaders());
        } catch (Exception e) {
            return processErrorResponse(e, new DeviceMetadataResponse(), logger);
        }

    }
}

Voici mon code de test:

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());
    }
}
9
Sat

Comme point de départ et démonstration pour le principal, vous pouvez commencer avec l'extrait de code suivant.

// define the headers you want to be returned
Map<String, String> headers = new HashMap<>();
headers.put(null, "HTTP/1.1 200 OK");
headers.put("Content-Type", "text/html");

// create an Enumeration over the header keys
Iterator<String> iterator = headers.keySet().iterator();
Enumeration headerNames = new Enumeration<String>() {
    @Override
    public boolean hasMoreElements() {
        return iterator.hasNext();
    }

    @Override
    public String nextElement() {
        return iterator.next();
    }
};

// mock HttpServletRequest
HttpServletRequest request = mock(HttpServletRequest.class);
// mock the returned value of request.getHeaderNames()
when(request.getHeaderNames()).thenReturn(headerNames);

System.out.println("demonstrate output of request.getHeaderNames()");
while (headerNames.hasMoreElements()) {
    System.out.println("header name: " + headerNames.nextElement());
}

// mock the returned value of request.getHeader(String name)
doAnswer(new Answer<String>() {
    @Override
    public String answer(InvocationOnMock invocation) throws Throwable {
        Object[] args = invocation.getArguments();
        return headers.get((String) args[0]);
    }
}).when(request).getHeader("Content-Type");

System.out.println("demonstrate output of request.getHeader(String name)");
String headerName = "Content-Type";
System.out.printf("header name: [%s]   value: [%s]%n", 
        headerName, request.getHeader(headerName));
}

production

demonstrate output of request.getHeaderNames()
header name: null
header name: Content-Type

demonstrate output of request.getHeader(String name)
header name: [Content-Type]   value: [text/html]
13
SubOptimal