You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@struts.apache.org by Timothy Astle <ti...@caris.com> on 2009/02/23 18:57:24 UTC

Writing a unit test that goes through result-types

I'm following the approach given here for writing unit tests for actions:
http://depressedprogrammer.wordpress.com/2007/06/18/unit-testing-struts-2-actions-spring-junit/

My Problem:
I want to write a unit test that will verify that getSettings() returns 
back a JSON string.  However, when I run the test, it does not go 
through the JSONResult type I have defined.  I'm wondering if it has to 
do with the BaseStrutsTestCase.createAction?  I noticed a snip inside of 
it that seems confusing (comment and code do not seem to agree)

<snip>
//do not execute the result after executing the action
proxy.setExecuteResult(true);
</snip>

I would figure if this is set to true, then it would go through my 
result and I would be able to get the stream from the Mock Response and 
check my JSON string.  However, it doesn't seem to be the case.

Below are some code snippets to help paint a picture if more details are 
required.


   @Test
    public void testGetSettings() throws Exception {
        Setting s1 = new Setting();
        s1.setId(0);
        s1.setName("Rocket Man");
        s1.setType(SettingType.STRING);
        s1.setDefaultValue("She packed my bags last night pre-flight");
        s1.setValue("Zero hour nine a.m.");

        // Add the setting to a list.
        List<Setting> settings = new ArrayList<Setting>(1);
        settings.add(s1);

        // Set the setting to the mock DAO
        MockSettingDAO settingDAO = new MockSettingDAO(settings);

        // Set the mock DAO on the service.
        SettingServiceImpl settingService = new SettingServiceImpl();
        settingService.setSettingDAO(settingDAO);

        // Set the service on the action.
        SettingAction action = createAction(SettingAction.class,
                "/configManager", "settingAction_getSettings", 
"getSettings");
        action.setSettingService(settingService);

        // Get the JSON string.
        String result = action.getSettings();

        // Check the result.
        assertEquals(result, Action.SUCCESS);

        MockHttpServletResponse response = (MockHttpServletResponse) 
ServletActionContext
                .getResponse();
        String jsonResult = response.getContentAsString();

// Validation of jsonResult would happen here.
    }

<snip_of_setting_service>

    /**
     * Get the settings as a JSON string.
     *
     * @return SUCCESS
     */
    public String getSettings() {
        List<Setting> settings = this.settingService.findAllSettings();
        ActionContext.getContext().put("jsonResult", settings);
        return Action.SUCCESS;
    }
</snip_of_setting_service>

<snip_of_struts_xml>
        <!--Result Types -->
        <result-types>
            <result-type name="JSONResult"
                
class="com.caris.sfe.web.configmanager.results.GenericJSONResult" />
        </result-types>
</snip_of_struts_xml>

<snip_of_json_result>
    @Override
    public void execute(ActionInvocation arg0) throws Exception {

        // retrieve your response, request and context objects.
        ServletActionContext.getResponse().setContentType("text/plain");
        HttpServletResponse response = ServletActionContext.getResponse();

        Object jsonResult = ActionContext.getContext().get("jsonResult");

        // Create your JSON object using third_party GSON library.
        Gson gson = new Gson();

        String gsonStr = "{\"Response\" : {\"Results\" : "
                + gson.toJson(jsonResult) + "}}";

        // write it out to the outputstream so that JSP can read it 
through the
        // response object.
        OutputStreamWriter outStreamWriter = new OutputStreamWriter(response
                .getOutputStream());
        outStreamWriter.write(gsonStr);
        outStreamWriter.flush();
    }
</snip_of_json_result>

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Writing a unit test that goes through result-types

Posted by Timothy Astle <ti...@caris.com>.
I found an article on how to statically load Tiles to get past the 
container issue.  I found a web site that explained how to initialize 
the tiles container.  See below:

<snip>
    protected void setUp() throws Exception {
        if (applicationContext == null) {
            // this is the first time so initialize Spring context
            servletContext = new MockServletContext();
            servletContext.addInitParameter(
                    ContextLoader.CONFIG_LOCATION_PARAM, CONFIG_LOCATIONS);
            applicationContext = (new ContextLoader())
                    .initWebApplicationContext(servletContext);

            // Struts JSP support servlet (for Freemarker)
            new JspSupportServlet().init(new 
MockServletConfig(servletContext));

            // Below is the fix I needed.

            // Statically configuring tiles since we do not load it from the
            // web.xml for tests.
            servletContext.addInitParameter(
                    BasicTilesContainer.DEFINITIONS_CONFIG,
                    "/WEB-INF/tiles-def-test.xml");
            final StrutsTilesListener tilesListener = new 
StrutsTilesListener();
            final ServletContextEvent event = new ServletContextEvent(
                    servletContext);
            tilesListener.contextInitialized(event);
        }
.....
</snip>

Timothy Astle wrote:
> Thanks for the tip Greg.  I quickly went through the debugger based on 
> the example here: 
> http://depressedprogrammer.wordpress.com/2007/06/18/unit-testing-struts-2-actions-spring-junit/
>
> and I learned two things.
>
> 1.  execute() does call getSettings().  All that CRUD nonsense was me 
> not being sure it was actually calling the method I wanted because it 
> threw an exception upon execution.
>
> 2.  It looks like adding the following to the createAction(..) method 
> fixed my first problem.  I had an interceptor putting a variable on 
> the session, but no session was set, triggering a NullPointerException.
>
> proxy.getInvocation().getInvocationContext().setSession(new HashMap());
>
> Now I'm just running into a problem where the 
> TilesAccess.getContainer(servletContext) is returning a null.  This is 
> in the org.apache.struts2.views.tiles.TilesResult class.
>
>     public void doExecute(String location, ActionInvocation 
> invocation) throws Exception {
>         setLocation(location);
>
>         ServletContext servletContext = 
> ServletActionContext.getServletContext();
>         TilesContainer container = 
> TilesAccess.getContainer(servletContext);
>
>         HttpServletRequest request = ServletActionContext.getRequest();
>         HttpServletResponse response = ServletActionContext.getResponse();
>
> // fails because the container is null
>         container.render(location, request, response);
>     }
>
> I will post my final results when I get that part figured out.  If 
> someone can offer a tip, I'd appreciate it.  I'm learning as I go here.
>
> Tim
>
>
> Greg Lindholm wrote:
>> You can take a look at this:
>>
>> http://glindholm.wordpress.com/2008/06/30/unit-testing-struts-2-actions/
>>
>> I've used it to unit test actions all the way through interceptors,
>> validation, actions, and results including freemarker result types.
>>
>>
>> Timothy Astle wrote:
>>   
>>> I had tried using proxy.execute(), which will use Struts.  Maybe that's 
>>> where I'm a bit lost.  I don't implement execute() because of my CRUD 
>>> approach.
>>>
>>> Can someone point me to some appropriate struts 2 junit tests so I can 
>>> figure this out?
>>>
>>>
>>>     
>>
>>   
>


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Writing a unit test that goes through result-types

Posted by Timothy Astle <ti...@caris.com>.
Thanks for the tip Greg.  I quickly went through the debugger based on 
the example here: 
http://depressedprogrammer.wordpress.com/2007/06/18/unit-testing-struts-2-actions-spring-junit/

and I learned two things.

1.  execute() does call getSettings().  All that CRUD nonsense was me 
not being sure it was actually calling the method I wanted because it 
threw an exception upon execution.

2.  It looks like adding the following to the createAction(..) method 
fixed my first problem.  I had an interceptor putting a variable on the 
session, but no session was set, triggering a NullPointerException.

proxy.getInvocation().getInvocationContext().setSession(new HashMap());

Now I'm just running into a problem where the 
TilesAccess.getContainer(servletContext) is returning a null.  This is 
in the org.apache.struts2.views.tiles.TilesResult class.

    public void doExecute(String location, ActionInvocation invocation) 
throws Exception {
        setLocation(location);

        ServletContext servletContext = 
ServletActionContext.getServletContext();
        TilesContainer container = TilesAccess.getContainer(servletContext);

        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();

// fails because the container is null
        container.render(location, request, response);
    }

I will post my final results when I get that part figured out.  If 
someone can offer a tip, I'd appreciate it.  I'm learning as I go here.

Tim


Greg Lindholm wrote:
> You can take a look at this:
>
> http://glindholm.wordpress.com/2008/06/30/unit-testing-struts-2-actions/
>
> I've used it to unit test actions all the way through interceptors,
> validation, actions, and results including freemarker result types.
>
>
> Timothy Astle wrote:
>   
>> I had tried using proxy.execute(), which will use Struts.  Maybe that's 
>> where I'm a bit lost.  I don't implement execute() because of my CRUD 
>> approach.
>>
>> Can someone point me to some appropriate struts 2 junit tests so I can 
>> figure this out?
>>
>>
>>     
>
>   


Re: Writing a unit test that goes through result-types

Posted by Greg Lindholm <gl...@yahoo.com>.
I always test against my real production struts.xml because I need to be sure
it is correct. I want my test to ensure the Actions, Results, and
Interceptors are all configured correctly.

I see your struts-test package does NOT extends="struts-default",  so you
are missing all the default configuration for interceptors etc. This may be
a big part of the problem.

As far as the objectFactory goes; if you are using Spring I can't really
help you as I don't use it.  My understanding is the objectFactory is what
Struts uses to create the Actions.  So if you want to create your own
actions and inject your own mock services etc. (and not use Spring) then you
may need to write your own objectFactory to do this.  And of course you
would have to configure struts to use your objectFactory.

Also I just updated StrutsTestContext
 at http://glindholm.wordpress.com/2008/06/30/unit-testing-struts-2-actions/
as there was a small tweak needed to support Struts 2.1.6.
StrutsTestContext.createActionProxy() now creates and sets the ActionContext
since it is no longer created lazily.


Timothy Astle wrote:
> 
> Hi Greg / all,
> 
> I've gone back to Greg's example and I'm getting the stack trace below.  
> From what I've read, it is because I'll need to define an object factory 
> for my test to run.  My application is using a combination of Struts 2 
> and Spring 2.  I've created a struts-test.xml that bypasses some of the 
> interceptors I want to skip for my action test.  In my tests, I'm 
> creating my own mock DAOs, mock Services and then manually assigning 
> them to my action.  When I run it, it fails.
> 
> I noticed in Greg's blog, he set a "struts.objectFactory" and mapped it 
> to guice.  (Which is something I don't know too much about.)
> 
> Possible related article:  
> http://www.nabble.com/Struts2-%2B-Spring2-ERROR---HELP!!!!-td17041898.html
> 
> 
> 
> Questions:
> 
> 1.  Does anyone have an example of how I would proceed to fix my problem?
> 
> 1.1  I'm not sure if I am supposed to map the object factory to a 
> specific type of factory. Spring, struts, or just mock it up?  What is 
> this object factory used for?  Keep in mind that I am manually assigning 
> services to my action and mock daos to my service.
> http://struts.apache.org/2.1.6/struts2-core/apidocs/com/opensymphony/xwork2/ObjectFactory.html
> 
> 2.  How do people normally configure a struts.xml for testing?
> 
> 
> 
> 
> 
> struts-test.xml
> 
> <?xml version="1.0" encoding="UTF-8" ?>
> <!DOCTYPE struts PUBLIC
>     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
>     "http://struts.apache.org/dtds/struts-2.0.dtd">
> <struts>
>     <!--constant name="blah.module" value="test.mymodule" /-->
>     <package name="configmanager" namespace="/configManager">
>        
>         <!--Result Types -->
>         <result-types>
>             <result-type name="JSONResult"
>                 class="a.b.c.web.configmanager.results.GenericJSONResult"
> />
>         </result-types>
>        
>         <!--Setting Actions -->
>         <action name="settingAction_getSettings" method="getSettings"
>             class="a.b.c.web.configmanager.action.SettingAction">
>             <result name="SUCCESS" type="JSONResult" />
>         </action>
>     </package>
> </struts>
> 
> 
> 
> com.opensymphony.xwork2.inject.DependencyException: 
> com.opensymphony.xwork2.inject.ContainerImpl$MissingDependencyException: 
> No mapping found for dependency 
> [type=com.opensymphony.xwork2.ObjectFactory, name='default'] in public 
> void 
> com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.setObjectFactory(com.opensymphony.xwork2.ObjectFactory).
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl.addInjectorsForMembers(ContainerImpl.java:144)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl.addInjectorsForMethods(ContainerImpl.java:113)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl.addInjectors(ContainerImpl.java:90)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl.addInjectors(ContainerImpl.java:86)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl$1.create(ContainerImpl.java:71)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl$1.create(ContainerImpl.java:69)
>     at 
> com.opensymphony.xwork2.inject.util.ReferenceCache$CallableCreate.call(ReferenceCache.java:150)
>     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
>     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
>     at 
> com.opensymphony.xwork2.inject.util.ReferenceCache.internalCreate(ReferenceCache.java:76)
>     at 
> com.opensymphony.xwork2.inject.util.ReferenceCache.get(ReferenceCache.java:116)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl.inject(ContainerImpl.java:483)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl$6.call(ContainerImpl.java:523)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl$6.call(ContainerImpl.java:522)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:574)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl.inject(ContainerImpl.java:521)
>     at 
> com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:188)
>     at 
> com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:55)
>     at 
> org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:360)
>     at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:403)
>     at 
> com.caris.sfe.web.configmanager.action.BaseStrutsTestCase.setUp(BaseStrutsTestCase.java:185)
>     at junit.framework.TestCase.runBare(TestCase.java:132)
>     at junit.framework.TestResult$1.protect(TestResult.java:110)
>     at junit.framework.TestResult.runProtected(TestResult.java:128)
>     at junit.framework.TestResult.run(TestResult.java:113)
>     at junit.framework.TestCase.run(TestCase.java:124)
>     at junit.framework.TestSuite.runTest(TestSuite.java:232)
>     at junit.framework.TestSuite.run(TestSuite.java:227)
>     at 
> org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:79)
>     at 
> org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
>     at 
> org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
>     at 
> org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
>     at 
> org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
>     at 
> org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
>     at 
> org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
> Caused by: 
> com.opensymphony.xwork2.inject.ContainerImpl$MissingDependencyException: 
> No mapping found for dependency 
> [type=com.opensymphony.xwork2.ObjectFactory, name='default'] in public 
> void 
> com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.setObjectFactory(com.opensymphony.xwork2.ObjectFactory).
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl.createParameterInjector(ContainerImpl.java:235)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl.getParametersInjectors(ContainerImpl.java:225)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.<init>(ContainerImpl.java:287)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl$3.create(ContainerImpl.java:117)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl$3.create(ContainerImpl.java:115)
>     at 
> com.opensymphony.xwork2.inject.ContainerImpl.addInjectorsForMembers(ContainerImpl.java:141)
>     ... 34 more
> 
> 
> 
> 
> 
> Greg Lindholm wrote:
>> You can take a look at this:
>>
>> http://glindholm.wordpress.com/2008/06/30/unit-testing-struts-2-actions/
>>
>> I've used it to unit test actions all the way through interceptors,
>> validation, actions, and results including freemarker result types.
>>
>>
>> Timothy Astle wrote:
>>   
>>> I had tried using proxy.execute(), which will use Struts.  Maybe that's 
>>> where I'm a bit lost.  I don't implement execute() because of my CRUD 
>>> approach.
>>>
>>> Can someone point me to some appropriate struts 2 junit tests so I can 
>>> figure this out?
>>>
>>>
>>>     
>>
>>   
> 
> 

-- 
View this message in context: http://www.nabble.com/Writing-a-unit-test-that-goes-through-result-types-tp22166625p22359701.html
Sent from the Struts - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Writing a unit test that goes through result-types

Posted by Timothy Astle <ti...@caris.com>.
Hi Greg / all,

I've gone back to Greg's example and I'm getting the stack trace below.  
>From what I've read, it is because I'll need to define an object factory 
for my test to run.  My application is using a combination of Struts 2 
and Spring 2.  I've created a struts-test.xml that bypasses some of the 
interceptors I want to skip for my action test.  In my tests, I'm 
creating my own mock DAOs, mock Services and then manually assigning 
them to my action.  When I run it, it fails.

I noticed in Greg's blog, he set a "struts.objectFactory" and mapped it 
to guice.  (Which is something I don't know too much about.)

Possible related article:  
http://www.nabble.com/Struts2-%2B-Spring2-ERROR---HELP!!!!-td17041898.html



Questions:

1.  Does anyone have an example of how I would proceed to fix my problem?

1.1  I'm not sure if I am supposed to map the object factory to a 
specific type of factory. Spring, struts, or just mock it up?  What is 
this object factory used for?  Keep in mind that I am manually assigning 
services to my action and mock daos to my service.
http://struts.apache.org/2.1.6/struts2-core/apidocs/com/opensymphony/xwork2/ObjectFactory.html

2.  How do people normally configure a struts.xml for testing?





struts-test.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <!--constant name="blah.module" value="test.mymodule" /-->
    <package name="configmanager" namespace="/configManager">
       
        <!--Result Types -->
        <result-types>
            <result-type name="JSONResult"
                class="a.b.c.web.configmanager.results.GenericJSONResult" />
        </result-types>
       
        <!--Setting Actions -->
        <action name="settingAction_getSettings" method="getSettings"
            class="a.b.c.web.configmanager.action.SettingAction">
            <result name="SUCCESS" type="JSONResult" />
        </action>
    </package>
</struts>



com.opensymphony.xwork2.inject.DependencyException: 
com.opensymphony.xwork2.inject.ContainerImpl$MissingDependencyException: 
No mapping found for dependency 
[type=com.opensymphony.xwork2.ObjectFactory, name='default'] in public 
void 
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.setObjectFactory(com.opensymphony.xwork2.ObjectFactory).
    at 
com.opensymphony.xwork2.inject.ContainerImpl.addInjectorsForMembers(ContainerImpl.java:144)
    at 
com.opensymphony.xwork2.inject.ContainerImpl.addInjectorsForMethods(ContainerImpl.java:113)
    at 
com.opensymphony.xwork2.inject.ContainerImpl.addInjectors(ContainerImpl.java:90)
    at 
com.opensymphony.xwork2.inject.ContainerImpl.addInjectors(ContainerImpl.java:86)
    at 
com.opensymphony.xwork2.inject.ContainerImpl$1.create(ContainerImpl.java:71)
    at 
com.opensymphony.xwork2.inject.ContainerImpl$1.create(ContainerImpl.java:69)
    at 
com.opensymphony.xwork2.inject.util.ReferenceCache$CallableCreate.call(ReferenceCache.java:150)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at 
com.opensymphony.xwork2.inject.util.ReferenceCache.internalCreate(ReferenceCache.java:76)
    at 
com.opensymphony.xwork2.inject.util.ReferenceCache.get(ReferenceCache.java:116)
    at 
com.opensymphony.xwork2.inject.ContainerImpl.inject(ContainerImpl.java:483)
    at 
com.opensymphony.xwork2.inject.ContainerImpl$6.call(ContainerImpl.java:523)
    at 
com.opensymphony.xwork2.inject.ContainerImpl$6.call(ContainerImpl.java:522)
    at 
com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:574)
    at 
com.opensymphony.xwork2.inject.ContainerImpl.inject(ContainerImpl.java:521)
    at 
com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:188)
    at 
com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:55)
    at 
org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:360)
    at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:403)
    at 
com.caris.sfe.web.configmanager.action.BaseStrutsTestCase.setUp(BaseStrutsTestCase.java:185)
    at junit.framework.TestCase.runBare(TestCase.java:132)
    at junit.framework.TestResult$1.protect(TestResult.java:110)
    at junit.framework.TestResult.runProtected(TestResult.java:128)
    at junit.framework.TestResult.run(TestResult.java:113)
    at junit.framework.TestCase.run(TestCase.java:124)
    at junit.framework.TestSuite.runTest(TestSuite.java:232)
    at junit.framework.TestSuite.run(TestSuite.java:227)
    at 
org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:79)
    at 
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
    at 
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at 
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
    at 
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
    at 
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
    at 
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: 
com.opensymphony.xwork2.inject.ContainerImpl$MissingDependencyException: 
No mapping found for dependency 
[type=com.opensymphony.xwork2.ObjectFactory, name='default'] in public 
void 
com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.setObjectFactory(com.opensymphony.xwork2.ObjectFactory).
    at 
com.opensymphony.xwork2.inject.ContainerImpl.createParameterInjector(ContainerImpl.java:235)
    at 
com.opensymphony.xwork2.inject.ContainerImpl.getParametersInjectors(ContainerImpl.java:225)
    at 
com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.<init>(ContainerImpl.java:287)
    at 
com.opensymphony.xwork2.inject.ContainerImpl$3.create(ContainerImpl.java:117)
    at 
com.opensymphony.xwork2.inject.ContainerImpl$3.create(ContainerImpl.java:115)
    at 
com.opensymphony.xwork2.inject.ContainerImpl.addInjectorsForMembers(ContainerImpl.java:141)
    ... 34 more





Greg Lindholm wrote:
> You can take a look at this:
>
> http://glindholm.wordpress.com/2008/06/30/unit-testing-struts-2-actions/
>
> I've used it to unit test actions all the way through interceptors,
> validation, actions, and results including freemarker result types.
>
>
> Timothy Astle wrote:
>   
>> I had tried using proxy.execute(), which will use Struts.  Maybe that's 
>> where I'm a bit lost.  I don't implement execute() because of my CRUD 
>> approach.
>>
>> Can someone point me to some appropriate struts 2 junit tests so I can 
>> figure this out?
>>
>>
>>     
>
>   

Re: Writing a unit test that goes through result-types

Posted by Greg Lindholm <gl...@yahoo.com>.
You can take a look at this:

http://glindholm.wordpress.com/2008/06/30/unit-testing-struts-2-actions/

I've used it to unit test actions all the way through interceptors,
validation, actions, and results including freemarker result types.


Timothy Astle wrote:
> 
> I had tried using proxy.execute(), which will use Struts.  Maybe that's 
> where I'm a bit lost.  I don't implement execute() because of my CRUD 
> approach.
> 
> Can someone point me to some appropriate struts 2 junit tests so I can 
> figure this out?
> 
> 

-- 
View this message in context: http://www.nabble.com/Writing-a-unit-test-that-goes-through-result-types-tp22166625p22186937.html
Sent from the Struts - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Writing a unit test that goes through result-types

Posted by Timothy Astle <ti...@caris.com>.
I had tried using proxy.execute(), which will use Struts.  Maybe that's 
where I'm a bit lost.  I don't implement execute() because of my CRUD 
approach.

Can someone point me to some appropriate struts 2 junit tests so I can 
figure this out?



Musachy Barroso wrote:
> you are creating an action and invoking a method on it, Struts is not
> involved at all in that. You might want to look at the struts junits
> to see how you can invoke an action.
>
> musachy
>
> On Mon, Feb 23, 2009 at 12:57 PM, Timothy Astle <ti...@caris.com> wrote:
>   
>> I'm following the approach given here for writing unit tests for actions:
>> http://depressedprogrammer.wordpress.com/2007/06/18/unit-testing-struts-2-actions-spring-junit/
>>
>> My Problem:
>> I want to write a unit test that will verify that getSettings() returns back
>> a JSON string.  However, when I run the test, it does not go through the
>> JSONResult type I have defined.  I'm wondering if it has to do with the
>> BaseStrutsTestCase.createAction?  I noticed a snip inside of it that seems
>> confusing (comment and code do not seem to agree)
>>
>> <snip>
>> //do not execute the result after executing the action
>> proxy.setExecuteResult(true);
>> </snip>
>>
>> I would figure if this is set to true, then it would go through my result
>> and I would be able to get the stream from the Mock Response and check my
>> JSON string.  However, it doesn't seem to be the case.
>>
>> Below are some code snippets to help paint a picture if more details are
>> required.
>>
>>
>>  @Test
>>   public void testGetSettings() throws Exception {
>>       Setting s1 = new Setting();
>>       s1.setId(0);
>>       s1.setName("Rocket Man");
>>       s1.setType(SettingType.STRING);
>>       s1.setDefaultValue("She packed my bags last night pre-flight");
>>       s1.setValue("Zero hour nine a.m.");
>>
>>       // Add the setting to a list.
>>       List<Setting> settings = new ArrayList<Setting>(1);
>>       settings.add(s1);
>>
>>       // Set the setting to the mock DAO
>>       MockSettingDAO settingDAO = new MockSettingDAO(settings);
>>
>>       // Set the mock DAO on the service.
>>       SettingServiceImpl settingService = new SettingServiceImpl();
>>       settingService.setSettingDAO(settingDAO);
>>
>>       // Set the service on the action.
>>       SettingAction action = createAction(SettingAction.class,
>>               "/configManager", "settingAction_getSettings", "getSettings");
>>       action.setSettingService(settingService);
>>
>>       // Get the JSON string.
>>       String result = action.getSettings();
>>
>>       // Check the result.
>>       assertEquals(result, Action.SUCCESS);
>>
>>       MockHttpServletResponse response = (MockHttpServletResponse)
>> ServletActionContext
>>               .getResponse();
>>       String jsonResult = response.getContentAsString();
>>
>> // Validation of jsonResult would happen here.
>>   }
>>
>> <snip_of_setting_service>
>>
>>   /**
>>    * Get the settings as a JSON string.
>>    *
>>    * @return SUCCESS
>>    */
>>   public String getSettings() {
>>       List<Setting> settings = this.settingService.findAllSettings();
>>       ActionContext.getContext().put("jsonResult", settings);
>>       return Action.SUCCESS;
>>   }
>> </snip_of_setting_service>
>>
>> <snip_of_struts_xml>
>>       <!--Result Types -->
>>       <result-types>
>>           <result-type name="JSONResult"
>>
>> class="com.caris.sfe.web.configmanager.results.GenericJSONResult" />
>>       </result-types>
>> </snip_of_struts_xml>
>>
>> <snip_of_json_result>
>>   @Override
>>   public void execute(ActionInvocation arg0) throws Exception {
>>
>>       // retrieve your response, request and context objects.
>>       ServletActionContext.getResponse().setContentType("text/plain");
>>       HttpServletResponse response = ServletActionContext.getResponse();
>>
>>       Object jsonResult = ActionContext.getContext().get("jsonResult");
>>
>>       // Create your JSON object using third_party GSON library.
>>       Gson gson = new Gson();
>>
>>       String gsonStr = "{\"Response\" : {\"Results\" : "
>>               + gson.toJson(jsonResult) + "}}";
>>
>>       // write it out to the outputstream so that JSP can read it through
>> the
>>       // response object.
>>       OutputStreamWriter outStreamWriter = new OutputStreamWriter(response
>>               .getOutputStream());
>>       outStreamWriter.write(gsonStr);
>>       outStreamWriter.flush();
>>   }
>> </snip_of_json_result>
>>
>> ---------------------------------------------------------------------
>> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
>> For additional commands, e-mail: user-help@struts.apache.org
>>
>>
>>     
>
>
>
>   

-- 



_________________________________________________________ 
Timothy Astle - Development Manager
Web Development Group
CARIS
115 Waggoners Lane, Fredericton, New Brunswick, Canada, E3B 2L4 
Tel: +1-506-458-8533  Fax: +1-506-459-3849
_________________________________________________________________________
Join us for CARIS 2010 in Miami, Florida, United States
Email caris2010@caris.com for details today
_________________________________________________________________________
This email and any files transmitted with it are confidential and intended 
only for the addressee(s). If you are not the intended recipient(s) please 
notify us by email reply. You should not use, disclose, distribute or copy 
this communication if received in error.

Any views or opinions expressed in this email are solely those of the 
author and do not necessarily represent those of the company. No binding 
contract will result from this email until such time as a written document 
is signed on behalf of the company.


Re: Writing a unit test that goes through result-types

Posted by Musachy Barroso <mu...@gmail.com>.
you are creating an action and invoking a method on it, Struts is not
involved at all in that. You might want to look at the struts junits
to see how you can invoke an action.

musachy

On Mon, Feb 23, 2009 at 12:57 PM, Timothy Astle <ti...@caris.com> wrote:
> I'm following the approach given here for writing unit tests for actions:
> http://depressedprogrammer.wordpress.com/2007/06/18/unit-testing-struts-2-actions-spring-junit/
>
> My Problem:
> I want to write a unit test that will verify that getSettings() returns back
> a JSON string.  However, when I run the test, it does not go through the
> JSONResult type I have defined.  I'm wondering if it has to do with the
> BaseStrutsTestCase.createAction?  I noticed a snip inside of it that seems
> confusing (comment and code do not seem to agree)
>
> <snip>
> //do not execute the result after executing the action
> proxy.setExecuteResult(true);
> </snip>
>
> I would figure if this is set to true, then it would go through my result
> and I would be able to get the stream from the Mock Response and check my
> JSON string.  However, it doesn't seem to be the case.
>
> Below are some code snippets to help paint a picture if more details are
> required.
>
>
>  @Test
>   public void testGetSettings() throws Exception {
>       Setting s1 = new Setting();
>       s1.setId(0);
>       s1.setName("Rocket Man");
>       s1.setType(SettingType.STRING);
>       s1.setDefaultValue("She packed my bags last night pre-flight");
>       s1.setValue("Zero hour nine a.m.");
>
>       // Add the setting to a list.
>       List<Setting> settings = new ArrayList<Setting>(1);
>       settings.add(s1);
>
>       // Set the setting to the mock DAO
>       MockSettingDAO settingDAO = new MockSettingDAO(settings);
>
>       // Set the mock DAO on the service.
>       SettingServiceImpl settingService = new SettingServiceImpl();
>       settingService.setSettingDAO(settingDAO);
>
>       // Set the service on the action.
>       SettingAction action = createAction(SettingAction.class,
>               "/configManager", "settingAction_getSettings", "getSettings");
>       action.setSettingService(settingService);
>
>       // Get the JSON string.
>       String result = action.getSettings();
>
>       // Check the result.
>       assertEquals(result, Action.SUCCESS);
>
>       MockHttpServletResponse response = (MockHttpServletResponse)
> ServletActionContext
>               .getResponse();
>       String jsonResult = response.getContentAsString();
>
> // Validation of jsonResult would happen here.
>   }
>
> <snip_of_setting_service>
>
>   /**
>    * Get the settings as a JSON string.
>    *
>    * @return SUCCESS
>    */
>   public String getSettings() {
>       List<Setting> settings = this.settingService.findAllSettings();
>       ActionContext.getContext().put("jsonResult", settings);
>       return Action.SUCCESS;
>   }
> </snip_of_setting_service>
>
> <snip_of_struts_xml>
>       <!--Result Types -->
>       <result-types>
>           <result-type name="JSONResult"
>
> class="com.caris.sfe.web.configmanager.results.GenericJSONResult" />
>       </result-types>
> </snip_of_struts_xml>
>
> <snip_of_json_result>
>   @Override
>   public void execute(ActionInvocation arg0) throws Exception {
>
>       // retrieve your response, request and context objects.
>       ServletActionContext.getResponse().setContentType("text/plain");
>       HttpServletResponse response = ServletActionContext.getResponse();
>
>       Object jsonResult = ActionContext.getContext().get("jsonResult");
>
>       // Create your JSON object using third_party GSON library.
>       Gson gson = new Gson();
>
>       String gsonStr = "{\"Response\" : {\"Results\" : "
>               + gson.toJson(jsonResult) + "}}";
>
>       // write it out to the outputstream so that JSP can read it through
> the
>       // response object.
>       OutputStreamWriter outStreamWriter = new OutputStreamWriter(response
>               .getOutputStream());
>       outStreamWriter.write(gsonStr);
>       outStreamWriter.flush();
>   }
> </snip_of_json_result>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
> For additional commands, e-mail: user-help@struts.apache.org
>
>



-- 
"Hey you! Would you help me to carry the stone?" Pink Floyd

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org