[英]Object cannot be cast to javax.servlet.http.HttpServletRequest with Spring WebFlow
I'm trying to integrate Spring MVC with Spring WebFlow. 我正在尝试将Spring MVC与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: 然后在webflow 之外的Controller中,我可以轻松获取会话数据:
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? 为什么我的测试抛出
ClassCastException
以及如何解决?
You can get HttpServletRequest
from RequestContext
by calling getRequest()
method. 您可以通过调用
getRequest()
方法从RequestContext
获取HttpServletRequest
。
Refer this Spring RequestContext Documentation 请参阅此Spring RequestContext文档
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
}
I checked my code again and I think the whole "problem" came from me trying to return Object
instead of HttpServletRequest
directly. 我再次检查了代码,我认为整个“问题”都来自于我试图直接返回
Object
而不是HttpServletRequest
。 Therefore, I caused ClassCastException
. 因此,我引起了
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.