Question

I need to write jUnit for Struts 2 action class.But action class is implementing ParameterAware interceptor which takes parameter map in HashMap and action class takes all request parameter from this hashmap

Action Class:

public class BrokerAction extends ActionSupport implements ServletRequestAware, ServletResponseAware,SessionAware,
        ParameterAware {

    /** The parameters. */
    private Map parameters;

    @Override
    public void setParameters(final Map param) {
        this.parameters = param;
    }

   public String getParameterValue(final String param) {
        final Object varr = getParameters().get(param);
        if (varr == null) {
            return null;    
        }
        return ((String[]) varr)[0];
    }

   public String getBrokerDetails()throws PactException{
        String id = getParameterValue("id");
   }

When i am putting data from Junit in request then it hasn't reflected in parameters map

Junit:

@Test
     public void testGetActionProxy() throws Exception {
        
         request.setAttribute("id", "23");
         ActionProxy proxy   =  getActionProxy("/getBrokerDetails");
         BrokerAction brokerAction = (BrokerAction) proxy.getAction();
         brokerAction.getBrokerDetails();
    }

Please help as how request data will be reflected in parameters map

Was it helpful?

Solution

Unit tests should be simple - instead of setting attributes on a request and using ActionProxy, why not just call setParameters to set your parameters? If your unit test is calling out to code that isn't in the class you are testing, then it becomes more complex and prone to failure for reasons not related to your code.

OTHER TIPS

The code to test the request parameter

<package name="test" namespace="/" extends="struts-default">
    <action name="getBrokerDetails" class="BrokerAction ">
        <result>/page.jsp</result>
    </action>
</package>


 public void testGetActionProxy() throws Exception {

     request.setParameter("id", "23");
     ActionProxy proxy   =  getActionProxy("/getBrokerDetails");
     BrokerAction brokerAction = (BrokerAction) proxy.getAction();

     String result = proxy.execute();
     assertEquals(Action.SUCCESS, result);

     assertEquals("23", brokerAction.getBrokerDetails());

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top