How can I unit test use this method in java?

I am working with Framework Struts2 and would like the unit test method executebelow:

public String execute() {
    setDao((MyDAO) ApplicationInitializer.getApplicationContext().getBean("MyDAO"));
    setUserPrincipal(); //fetches attribute from request and stores it in a var
    setGroupValue(); //
    setResults(getMyDao().getReportResults(getActionValue(), getTabName());
    setFirstResultSet((List) getResults()[0]);
    setSecondResultSet((List) getResults()[1]);
    return SUCCESS;
}

As you can see, most of the logic is database related. So how can I use a module to test this functionality? I would like to unit test by mocking HTTPServletRequestwith several query variables inside it.

My questions:

  • How can I fake / mock a query variable as if it were from a browser
  • Should my unit test call the actual DAO and make sure the data is returned?
  • If so, how can I call the DAO from unit test, since the DAO is bound to the server, since the jndi pool settings are on the application server.

I would appreciate any book / article that shows how to do this.

+3
3

, , , .

setDao((MyDAO) ApplicationInitializer.getApplicationContext().getBean("MyDAO"));

, . , ApplicationInitializer. getApplicationContext() ApplicationContext. MyDAO, getBean("MyDAO"). , .


setUserPrincipal(); //fetches attribute from request and stores it in a var

? ? , , . MockHttpServletRequest.


setGroupValue(); //

, ? , , ?


setResults(getMyDao().getReportResults(getActionValue(), getTabName());

-, getReportResults() .


setFirstResultSet((List) getResults()[0]);
setSecondResultSet((List) getResults()[1]);

, - . , getReportResults(), .


return SUCCESS;

, SUCCESS .


/ ,

. , Spring.

unit test DAO , ?

unit test DAO, unit test. .

, DAO unit test, DAO , jndi .

, . , , . - DataSource .


, Struts. , mocks . , execute(), , , . .


  • Struts 2 Spring. , Spring MyDAO . .
+6

unit test, Spring (.. ) factory. , bean, , . DAO . , DAO .

, . DAO , . DAO, DAO , , ( unit test). , DAO unit test .

, HttpServletRequest ( , ), , . setXxx, .

+1
  • HTTPServletRequest, ? Selenium, .

  • DAO ( ) HSQLDB, / , / . HSQLDB , , . , . , .

  • The easiest way to make your daos injected available to your tests is to let your unit test classes extend AbstractJUnit4SpringContextTests. You can then use the annotation @ContextConfigurationto point to multiple xml application context files, or if you are using an annotation-based configuration, specify it in your context file that has the declaration <context:annotation-config />.

0
source

All Articles