I'm wondering on a request pass to a method and pulling the HttpSession?
Following from JUnit:
#Test
public void testSessionPass(){
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpSession session = createMock(HttpSession.class);
expect(session.getAttribute("testAttribute")).andReturn("testValue").anyTimes();
replay(request);
replay(session);
CAction cAction = new CAction();
cAction.test(request);
}
In the CAction:
public void test (HttpServletRequest request){
HttpSession session = request.getSession();
if(session.getAttribute("testAttribute")!=null){
System.out.println((String)session.getAttribute("testAttribute"));
}
}
UPDATE:
Why am I loosing the session from the passed request value at line HttpSession session = request.getSession(); ??
You aren't mocking the call to getSession()
Add this line before your calls to replay()
expect(request.getSession()).andReturn(session);
Related
Is there any way to test this using JUnit and Mockito?
Below is a method that I want to test
#RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logoutPage(HttpServletRequest request, HttpServletResponse response)
{
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null)
{
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout";
}
Test for logout
#Test
public void testLogoutPage() throws Exception
{
MockHttpServletRequestBuilder requestBuilder = get("/logout");
MockMvcBuilders.standaloneSetup(this.loginController)
.build()
.perform(requestBuilder)
.andExpect(status().isFound())
.andExpect(MockMvcResultMatchers.model().size(0))
.andExpect(view().name("redirect:/login?logout"))
.andExpect(MockMvcResultMatchers.redirectedUrl("/login?logout"));
}
Test covers everything except.
new SecurityContextLogoutHandler().logout(request, response, auth);
I tried some assertions, but always get NullPointerException.
I have to send JSON data from one service method to the other using postForObject() method.
I saw one example on RestTemplate on this link.
postForObject() method has the following format:
User returns = rt.postForObject(uri, u, User.class, vars);
Or
User returns = rt.postForObject(uri, u, User.class);
I want to know that, after using postForObject() method, if we implement the service method to accept the User object, how it will look like?
In my project, I have code like
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
String uri = "http://testcode.com/myapp/api/launchservices";
ServiceRequest request = new ServiceRequest();
request.setId(UUID.randomUUID().toString());
....
I am getting error at this line:
ServiceRequest req = restTemplate.postForObject(uri, request, ServiceRequest.class);
while executing this, I am getting this error mesage:
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:88)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:537)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:493)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:452)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:302)
my implementation method is:
#RequestMapping(value = "/launchservices", method = RequestMethod.POST)
#ResponseBody
public boolean launchServices(#PathVariable ServiceRequest request) {
System.out.println("Request: "+request.toString());
return true;
}
How to get rid of this? What will be the URI?
I got solution to this problem.
In this example,method postForObject returns an object of class "ServiceRequest"
ServiceRequest req = restTemplate.postForObject(uri, request, ServiceRequest.class);
So, the method that implements this service with the above 'uri' should return an object of class ServiceRequest
All it needs is, slight modification in implementation method as below
#RequestMapping(value = "/launchservices", method = RequestMethod.POST, headers = "Accept=application/json")
#ResponseBody
public ServiceRequest launchServices(#RequestBody ServiceRequest request) {
System.out.println("Request: "+request.toString());
return request;
}
im doing test for one method with junit and mockito. I want to test if a .setatribute in httpsession is ok.
This is my code:
#Test
#PrepareForTest({PortalUtil.class})
public void changeStagingSourceUrlValueLive(){
ActionRequest request = mock(ActionRequest.class);
ActionResponse response = mock(ActionResponse.class);
HttpSession httpSession = mock(HttpSession.class);
HttpServletRequest httpServletSession = mock(HttpServletRequest.class);
StagingActions stagingActions = new StagingActions();
PowerMockito.mockStatic(PortalUtil.class);
when(request.getParameter("stagingStatusIsUse")).thenReturn("false");
when(PortalUtil.getHttpServletRequest(request)).thenReturn(httpServletSession);
when(httpServletSession.getSession()).thenReturn(httpSession);
stagingActions.changeStagingSourceUrlValue(request, response);
String attribute = (String) httpSession.getAttribute(KeyConstants.STAGING_URL_STATUS_KEY.getKey());
assertFalse(Boolean.valueOf(attribute));
}
The method changeStagingSourceUrlValue is correct, im sure, but in my test, when i do a getAttribute always return me null.
Must i to do anything before or after call my method to can get attributes of mock httpsession?.
Thanks.
I have a Rest Controller method using Spring 3.1 that looks like this:
#RequestMapping(value="/user", method=RequestMethod.POST, consumes={MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<String> addUser(#RequestBody #Valid User user){
System.out.println("called / user method");
try{
user = userService.addUser(user);
return responseBuilder.addApiResourceSucceeded(user,null);
}catch(Exception e){
return responseBuilder.apiActionFailed("user already exists", HttpStatus.CONFLICT);
}
}
I have test which looks like this:
#Before
public void setUp() {
adapter = new AnnotationMethodHandlerAdapter();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
mapper = new ObjectMapper();
}
#Test
public void testAddUser() throws Exception {
request.setMethod("POST");
request.setContentType(MediaType.APPLICATION_JSON_VALUE);
request.setRequestURI("/user");
ObjectNode userJson = mapper.createObjectNode();
userJson.put("userId", "jonnybz");
userJson.put("email", "test#gmail.com");
userJson.put("password", "password");
userJson.put("longitude",-10.127205999);
userJson.put("latitude", 57.252269);
ArrayNode arrNode = mapper.createArrayNode();
arrNode.add(-10.1272059999);
arrNode.add(57.2522);
userJson.put("lonLat",arrNode);
request.setContent(mapper.writeValueAsBytes(userJson));
adapter.handle(request, response, userController);
String content = response.getContentAsString();
assertEquals(200, response.getStatus());
User user = dao.listAll().get(0);
objectId = user.getId();
assertNotNull(objectId);
}
When I execute a call against this endpoint from my client app (developed with angular) it works great, but when I run my test I get an " Content type 'application/json' which is coming from a HttpMediaTypeNotSupportedException" error that I cannot track down. The request never seems to hit my method. Am I missing something simple here?
Solved this problem by switching to the spring-mvc-test framework and building my test like this:
#Test
public void testAddUser() throws Exception {
ObjectNode userJson = mapper.createObjectNode();
userJson.put("userId", "jonnbz");
userJson.put("email", "test#gmail.com");
userJson.put("password", "password");
userJson.put("longitude",-10.667205999);
userJson.put("latitude", 74.252269);
ArrayNode arrNode = mapper.createArrayNode();
arrNode.add(-10.667205999);
arrNode.add(74.252269);
userJson.put("lonLat",arrNode);
MvcResult res = MockMvcBuilders.xmlConfigSetup("classpath:test-context.xml").build()
.perform(MockMvcRequestBuilders.post("/user")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.body(mapper.writeValueAsBytes(userJson)))
.andExpect(status().isOk())
.andExpect(content().type(MediaType.APPLICATION_JSON))
.andReturn();
System.out.println(res.getResponse().getContentAsString());
}
You should also include a Accept header of "application/json" in your test, since you have included a consumes="application/json", Spring MVC will match the Accept header value to the consumes value and only then call the mapped method.
I have a servlet method where i need to pass a json object. This json object will be created in one of the managed bean(JSF). I just tried injecting the bean into the servlet to get the json object, but i am getting runtime exception, may be it is not possible that way. So i want to call the servlet from JSF bean. Any ideas how to call from the bean?
Servlet
private static final long serialVersionUID = 1L;
TopicController topicController;
TopicBean topicBean;
List<JsonTopicObj> jsonTopicList;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
// here code for subscription
Meteor mateor = Meteor.build(req).addListener(
new MyAtmosphereResourceEventListener());
boolean isLongPolling = true;
if (mateor.transport() == LONG_POLLING) {
isLongPolling = true;
} else {
isLongPolling = false;
}
System.out.println(" Now in the Get method of Atmosphere");
// create the broadcaster for the particular topic
String topicId = "default"; // for all users right now
Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(
topicId, true);
//set that broeadcaster
mateor.setBroadcaster(broadcaster);
mateor = mateor.resumeOnBroadcast(isLongPolling);
mateor.suspend(-1);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException {}
JSF BEAN
#ManagedBean(name = "testController")
#RequestScoped
public void listAllTopics() {
JsonTopicObj jsonTopicObj;
StringWriter out = new StringWriter();
JsonFactory jfactory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper();
jsonTopicList = new ArrayList<JsonTopicObj>();
for (int i = 0; i < topicBean.getTopicVOArray().length; i++) {
jsonTopicObj = new JsonTopicObj();
......................
}
mapper.writeValue(out, jsonTopicList);
now i need to call the servlet dopost method and send "out.toString()"
Where is your first control? Does it go to managed bean and then servlet
and this bean is responsible for forwarding to the servlet? If it is so,
you can create the JSON object, get your request and response from FacesContext
and dispatch the request to the servlet.
FacesContext give your request and response and from that you can dispatch your
request.