我尝试了这样的事情,但仍然抛出NullPointerException。
@RunWith(MockitoJUnitRunner.class)
public class MyActionTest extends BaseActionTestCase {
@Mock private ServletActionContext context;
@Mock
private serviceclass serviceMock;
@InjectMocks
private MyAction action;
@Test
public void testSave() throws Exception {
when(serviceMock.getTaskCode()).thenReturn("tc");
action.save();
verify(serviceMock).saveObject(any(Task.class));
}
发布堆栈跟踪:
java.lang.NullPointerException
at org.apache.struts2.ServletActionContext.getRequest(ServletActionContext.java:112)
at com.princess.ilo.webapp.action.BaseAction.getRequest(BaseAction.java:176)
at com.princess.ilo.webapp.action.BaseAction.getSession(BaseAction.java:198)
at com.princess.ilo.webapp.action.BaseAction.getUser(BaseAction.java:206)
at com.princess.ilo.webapp.action.TaskAction.save(TaskAction.java:116)
at com.princess.ilo.webapp.action.TaskActionTest.testSave(TaskActionTest.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests
嗯,我想说你仍然需要创建动作对象,比如
@InjectMocks private MyAction action = new MyAction();
有关一些示例,请参阅 http://docs.mockito.googlecode.com/hg/org/mockito/InjectMocks.html