2014-01-22 30 views
2

期間返回null我正在經由行家JUnit測試其中支柱作用的java方法正在被測試,使得下面的調用:ActionContext.getContext()getParameters()StrutsJUnit4TestCase

// Gets this from the "org.apache.struts2.util.TokenHelper" class in the struts2-core jar 
String token = TokenHelper.getTokenName(); 

這裏是方法在 「TokenHelper.java」:

/** 
* Gets the token name from the Parameters in the ServletActionContext 
* 
* @return the token name found in the params, or null if it could not be found 
*/ 
public static String getTokenName() { 

    Map params = ActionContext.getContext().getParameters(); 

    if (!params.containsKey(TOKEN_NAME_FIELD)) { 
     LOG.warn("Could not find token name in params."); 

     return null; 
    } 

    String[] tokenNames = (String[]) params.get(TOKEN_NAME_FIELD); 
    String tokenName; 

    if ((tokenNames == null) || (tokenNames.length < 1)) { 
     LOG.warn("Got a null or empty token name."); 

     return null; 
    } 

    tokenName = tokenNames[0]; 

    return tokenName; 
} 

在此方法中的第一行被返回null

Map params = ActionContext.getContext().getParameters(); 

下一個LOC下,「params.containKey(...)」拋出NullPointerException,因爲「params」爲空。

當這個動作被正常調用,這運行正常。但是,在JUnit測試期間,會出現該空指針。

我的測試類是這樣的:

@Anonymous 
public class MNManageLocationActionTest extends StrutsJUnit4TestCase { 

    private static MNManageLocationAction action; 

    @BeforeClass 
    public static void init() { 
     action = new MNManageLocationAction(); 
    } 

    @Test 
    public void testGetActionMapping() { 
     ActionMapping mapping = getActionMapping("/companylocation/FetchCountyListByZip.action"); 
     assertNotNull(mapping); 
    } 

    @Test 
    public void testLoadStateList() throws JSONException { 
     request.setParameter("Ryan", "Ryan"); 

     String result = action.loadStateList(); 

     assertEquals("Verify that the loadStateList() function completes without Exceptions.", 
       result, "success"); 
    } 
} 

的ActionContext.getContext()至少不再爲空後,我轉而使用StrutsJUnit4TestCase。

任何想法爲什麼.getParameters()返回null?

回答

2

您需要在您的測試方法中自行初始化參數映射。此外,如果您想獲取令牌名稱,則需要將其放入參數映射中。

Map<String, Object> params = new HashMap<String, Object>(); 
params.put(TokenHelper.TOKEN_NAME_FIELD, 
         new String[] { TokenHelper.DEFAULT_TOKEN_NAME }); 
ActionContext.getContext().setParameters(params); 
相關問題