I use Java EE 6 running on GlassFish and Jersey.
How can I mock a request to this resource with some custom headers, and some other request details?
@Stateless
@Path("/user")
public class Resources {
@Contex
private HttpServletRequest request;
....
@GET
@Path("/settings")
@Produces("application/json")
@Consumes("text/plain")
public AccountSettings accountSettings() {
//check custom headers and request content do some stuff
return accountSettings;
}
....
}
And this is my java code, but I get null pointer exception on res.accountSettings() because request is still null.
@Mock
HttpServletRequest request= Mockito.mock(HttpServletRequest.class);
@Test
public void testResources() {
when(request.getHeader(HTTP_AUTHORIZATION_HEADER)).thenReturn("Basic wedwd");
Resources res=new Resources();
AccountSettings response=res.accountSettings();
}
Instead of create with new keyword, When I use this then I also get the resources null.
@Inject Resources resources
I believe you can do as follow with an @InjectMocks annotation, it outside any JAXRS context or CDI injection stuff, it treated as a regular java class.
@RunWith(MockitoJUnitRunner.class)
public class ResourcesTest {
@Mock HttpServletRequest request;
@InjectMocks Resources res;
@Test
public void testResources() {
// given
when(request.getHeader(HTTP_AUTHORIZATION_HEADER)).thenReturn("Basic wedwd");
// when
AccountSettings response = res.accountSettings();
// then
...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.