2

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.

colymore
  • 11,776
  • 13
  • 48
  • 90
  • Your httpSession object is a Mock and you have not specified any behaviour for the "getAttribute" method. Are you assuming that your method changeStagingSourceUrlValue calls a setAttribute and you want to check that it was really done? What are you trying to achieve with your test? – Martin Nov 25 '13 at 10:51
  • 4
    You could try: `verify(httpSession, times(1)).setAttribute(KeyConstants.STAGING_URL_STATUS_KEY.getKey(), true);`. However, you would have to define something like: `when(request.getSession()).thenReturn(httpSession);` or something similar that matches your structure. Would that solve what you are trying to do? – Martin Nov 25 '13 at 11:51
  • I need to test if my method changeStagingSourceUrlValue really set a attribute in a session..This isnt the correct way? – colymore Nov 26 '13 at 10:44
  • 1
    Well, as it is it is not the right way. I will try to explain why: the httpSession and your request/response objects are mocks. That means, you just create a "dummy" object that implements the interface. However, the behaviour of these objects is only defined with your "when" statements, so, the way you are doing it, you cannot know if the Attribute is set as your mock object does not implement the set/get functionality and you request/response and session objects are not related. You need to structure your test so you can test what you need. That's why I recommended the "times" aproach. – Martin Nov 26 '13 at 12:16

0 Answers0