Strut 2.3.1.2 Unit test, how to remove Spring codependency vs NPE with getContext()

后端 未结 1 1468
梦毁少年i
梦毁少年i 2020-12-22 08:44

I\'m just upgrading to Struts 2.3.1.2, and having a few issues with JUnit tests.

My old test code was like this....

public class HomeActionTest  {

          


        
相关标签:
1条回答
  • 2020-12-22 09:13

    You should indeed keep your unit test as fast as possible (otherwise, no TDD). So you should do the minimum struts setup: (I'm using mockito and I have this code in a static block, full code in this gist)

    ActionContext actionContext = mock(ActionContext.class);
    ServletContext servletContext = mock(ServletContext.class);
    when(actionContext.getLocale()).thenReturn(Locale.FRENCH);
    ValueStack valueStack = mock(ValueStack.class);
    Map<String, Object> context = new HashMap<String,Object>();
    Container container = mock(Container.class);
    XWorkConverter conv = mock(XWorkConverter.class);
    when(container.getInstance(XWorkConverter.class)).thenReturn(conv);
    when(conv.convertValue(any(Map.class), any(Object.class), any(Class.class))).thenAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            log.info(invocation.getArguments()[1].toString());
            return "VALUE";
        }
    
    });
    context.put(ActionContext.CONTAINER, container);
    when(valueStack.getContext()).thenReturn(context);
    when(actionContext.getValueStack()).thenReturn(valueStack);
    ServletActionContext.setContext(actionContext);
    ServletActionContext.setServletContext(servletContext);
    
    0 讨论(0)
提交回复
热议问题