How to get the HTML output of an Action in Struts 2 unit test?

830 Views Asked by At

In struts 2 unit tests, the class MockHttpServletResponse is available which I'm expecting, should contain the html output of any given action after it is executed. I'm trying to obtain this output and test it for the presence of a certain string, however I'm getting an empty string returned as the output.

Here's my code:

public class HomeTest extends StrutsJUnit4TestCase<Home>
{    
    private ActionProxy proxy;

    @Before
    public void setUp() throws Exception
    {
        super.setUp();
        proxy = getActionProxy("/home");
    }

    //This test passes fine, the problem is in the next test:
    @Test
    public void testExecute() throws Exception
    {
       String result = proxy.execute();        
       assertEquals("Landing", "landing", result);                
    }

    @Test
    public void testAssets() throws Exception
    {  
        proxy.execute();

        String output = response.getContentAsString();
        System.out.println("output : " + output);

        //The following assertion fails, and in the console, I see an empty
        //String for the output:
        assertTrue( output != null && ! output.isEmpty() );

        String cdnUrl = Config.getCDNUrl();
        assertTrue( output.contains(cdnUrl) );
    }
}

Here's how I configured this action in my struts.xml file:

 <action name="home" class="net.myProj.actions.Home" method="execute">
    <result name="landing">/landing.jsp</result>
 </action>       

If I visit this action normally in my browser, I can see the expected html output just fine. But if I try to run the test, then I can't get the same output using response.getContentAsString(). What am I doing wrong?

0

There are 0 best solutions below