使用junit测试structs的action时出现 java.lang.NullPointerException at org.apache.struts2.StrutsTestCase.getActionProxy
代码:
package action;
import dao.UserDao;
import org.apache.struts2.StrutsSpringTestCase;
import org.apache.struts2.StrutsTestCase;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import com.opensymphony.xwork2.ActionProxy;
import service.UserService;
import java.util.HashMap;
import java.util.Map;
import static org.easymock.EasyMock.replay;
public class LoginActionTest extends StrutsSpringTestCase {
protected String[] getContextLocations() {
return new String[] { "struts.xml", "applicationContext.xml" };
}
private UserService userService;
@Before
public void setUp() throws Exception{
userService = EasyMock.createMock(UserService.class);
}
@Test
public void testExecute() throws Exception {
ActionProxy proxy = getActionProxy("/loginAction");
LoginAction test = (LoginAction) proxy.getAction();
assertNotNull(test);
test.setUsername("u1");
test.setPassword("1");
Map session=new HashMap();
test.setSession(session);
test.setUserService(userService);
EasyMock.expect(userService.loginVerify("u1","1")).andReturn(true);
replay(userService);
String result = proxy.execute();
assertEquals("success", result);
}
}
报错:
java.lang.NullPointerException
at org.apache.struts2.StrutsTestCase.getActionProxy(StrutsTestCase.java:131)
at action.LoginActionTest.testExecute(LoginActionTest.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:252)
at junit.framework.TestSuite.run(TestSuite.java:247)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
原因是我覆盖了继承的StrutsSpringTestCase的setUp函数 需要加上super.setUp()才能正确
@Before
public void setUp() throws Exception{
super.setUp();
userService = EasyMock.createMock(UserService.class);
}
|