Object cannot be cast to javax.servlet.http.HttpServletRequest with Spring WebFlow

9.3k Views Asked by At

I'm trying to integrate Spring MVC with Spring WebFlow. In order to share session data between both of them I came up with this solution that actually works fine:

public String prepareForPayment(RequestContext context, Authentication currentUser) {
    PaymentDetails paymentDetails = new PaymentDetails();

    // CODE HERE

    HttpServletRequest request =       (HttpServletRequest)context.getExternalContext().getNativeRequest();
    request.getSession().setAttribute("paymentDetails", paymentDetails);

    // CODE HERE

}

Then in a Controller outside webflow I can easily get session data:

PaymentDetails paymentDetails = (PaymentDetails)session.getAttribute("paymentDetails");

So above code works fine and I'm able to set and get session attributes.

Now, when I write a test for this class I get:

java.lang.ClassCastException: java.lang.Object cannot be cast to javax.servlet.http.HttpServletRequest

Why my test is throwing ClassCastException and how to solve it?

3

There are 3 best solutions below

0
On BEST ANSWER

I checked my code again and I think the whole "problem" came from me trying to return Object instead of HttpServletRequest directly. Therefore, I caused ClassCastException. This piece of code works fine:

@RunWith(MockitoJUnitRunner.class)
public class Test {
    @Mock
    private RequestContext           context;

    @Mock
    private ExternalContext          externalContext;

    @Mock
    private HttpServletRequest       httpServletRequest;

    @Mock
    private HttpSession              httpSession;

    @Before
    public void setup() {
        Mockito.when(context.getExternalContext()).thenReturn(externalContext);
        Mockito.when(externalContext.getNativeRequest()).thenReturn(httpServletRequest);
        Mockito.when(httpServletRequest.getSession()).thenReturn(httpSession);
    }
}
4
On

You can get HttpServletRequest from RequestContext by calling getRequest() method.

Refer this Spring RequestContext Documentation

0
On

I rewritten some of the code and in the end I used:

PaymentDetails paymentDetails = (PaymentDetails) context.getConversationScope().get("paymentDetails");

and in my test:

@Mock
private RequestContext context;

@Mock
private MutableAttributeMap attMap;

private PaymentDetails paymentDetails = new PaymentDetails();

// CODE HERE

@Before
public void setUp() throws Exception {
    // Use paymentDetails methods and set values. For example:
    paymentDetails.setCurrency("GBP");

    // CODE HERE

    Mockito.when(context.getConversationScope()).thenReturn(attMap);
    Mockito.when(attMap.get("paymentDetails")).thenReturn(paymentDetails);
    // CODE HERE
}