2011-12-15 108 views
0

我想單元測試我的驗證定義與註釋。但它應該很輕。無需加載任何配置文件。我對struts2比較陌生,所以我不確定它是否可能。我有MyAction與方法:單元測試沒有配置文件的struts2註釋驗證

@Validations(...) 
public String submit() {...} 

,我想的是一樣的東西:

@Test 
public void submitTest() { 
    MyAction myAction = createInitializedMyAction(); //new MyAction, setXXX 
    Map<String, String> httpRequestParams = prepareHttpRequestParams(); 
    TestHelperINeed testHelper = createTestHelper(myAction); // maybe some proxy??? 
    testHelper.execute("submit", httpRequestParams); 

    assertErrors(testHelper.getErrors()); 
    assertResult(testHelper.getResult()); 

每一個解決方案,我發現需要Struts和Spring的配置文件。爲什麼我需要它們,如果我想測試的所有代碼位於單個java文件中?

回答

0

,我發現有一個解決方案:http://bloodredsun.com/2009/10/21/unit-testing-struts2-actions-with-annotation-based-validation/

它需要小的重構,使之更加有用的,但它的工作原理。至少在Struts 2.1.6中。我還添加了一些更改,以使其可以用作我的生產支柱:

 
builder.constant("devMode", "false"); 
builder.constant("objectFactory.classloader", ActionAnnotationValidatorFactory.class.getClassLoader().getClass()); 

Container container = builder.create(true); 
ValueStackFactory ognlValueStackFactory = container.getInstance(ValueStackFactory.class); 
((OgnlValueStackFactory) ognlValueStackFactory).setAllowStaticMethodAccess("true"); 

它需要稍作更改才能使用struts 2.1.8.1。在致電validate之前,我會這樣做:

 
ActionInvocation actionInvocation = Mockito.mock(ActionInvocation.class, Mockito.RETURNS_DEEP_STUBS); 
ActionContext.getContext().setActionInvocation(actionInvocation);