SpringMVC- Mockito- Junit - 从控制器类调用服务类方法时的NullPointerException

时间:2015-02-19 10:43:24

标签: spring mongodb spring-mvc junit mockito

我正在使用spring MVC编写一个Web应用程序。我创建了一个服务类,使用UI将数据映射到数据库或从数据库映射。

我的问题是我是junit和mockito的新手 当我试图在Controller类上编写单元测试时,它总是返回一个NullPointerException。因为我无法找到答案,所以真的很烦人,所以我希望你们能帮助我。下面我发布了我的代码。

我的Controller类方法on / update返回成功

@RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateFormData(@ModelAttribute CRDetails certGuide,
            ModelMap model) { 
        crService.updateCertification(certGuide);
        return "success";   
}

我的服务类方法使用修改后的数据更新mongodb

public void updateCertification(CRDetails certGuide) {      String userTypeSubmitted = certGuide.getCertGuidelines().getUserType();         System.out.println("updated by " + userTypeSubmitted);      Update update = new Update();       Query query = new Query(Criteria.where("cr").is("CR1"));

        CRDetails details = certMongoTemplate.findOne(query, CRDetails.class,
                COLLECTION_NAME);       CertificateGuidelines newCertGuide = new CertificateGuidelines();

        if (details != null) {          newCertGuide.setCertG(certGuide.getCertGuidelines().getCertG());            if (userTypeSubmitted.equals("Certification Team")
                    && userTypeSubmitted != "") {
                newCertGuide.setStatus("Pending with Document Developer");          } else {
                newCertGuide.setStatus("Pending with Certification Team");          }           newCertGuide.setHistoryCount(++count);

            // converting it into mongo document.           MongoConverter converter = certMongoTemplate.getConverter();            DBObject newRec = (DBObject) converter
                    .convertToMongoType(newCertGuide);          update.set("certGuidelines", newRec);       }

        System.out.println("new cert guide " + newCertGuide.getCertG() + " "
                + newCertGuide.getStatus() + " "
                + newCertGuide.getHistoryCount() + " "
                + newCertGuide.getUserType());
                certMongoTemplate.updateFirst(query, update, CRDetails.class); }

我的controllerTest类返回NullPointerException

import static org.junit.Assert.assertEquals;

import org.junit.Before; 
import org.junit.Test; 
import org.mockito.InjectMocks; 
import org.mockito.Mock;  
import org.mockito.Mockito; 
import org.springframework.test.web.server.MockMvc; 
import org.springframework.ui.ModelMap; 
import org.springframework.web.servlet.View;

import com.cerner.docworks.controller.CRController; 
import com.cerner.docworks.domain.CRDetails; 
import com.cerner.docworks.service.CRService;


public class CRControllerTest  {

    /*@Mock     private CRService service;*/
    @Mock   View mockView;

   @InjectMocks      
   private CRController crController;

    private MockMvc mockMvc;

     @Before     public void setup() {
             }

    @Test   public void testUpdate() throws Exception {          //     CRService service = Mockito.mock(CRService.class);      CRService crService = Mockito.spy(new CRService());         ModelMap model = Mockito.mock(ModelMap.class);      CRDetails certGuide = Mockito.spy(new CRDetails());
                CRController controller = new CRController();

                 //     Mockito.when(service.updateCertification(certGuide)); //        Mockito.when(model.addAttribute(Matchers.eq("certGuide"),any(String.class))).thenReturn(null); //       Mockito.doThrow(new RuntimeException()).when(crService).updateCertification(certGuide);         Mockito.doNothing().when(crService).updateCertification(certGuide);         Mockito.mockingDetails(certGuide); //       Mockito.doCallRealMethod().when(crService).updateCertification(certGuide); //       Mockito.(crService)).updateCertification(certGuide);;       String fileName = controller.updateFormData(certGuide, model);
                System.out.println(fileName); //        Mockito.verify(controller).updateFormData(certGuide, model);        assertEquals("success", fileName);  } }

跟踪:

  

java.lang.NullPointerException at   com.cerner.docworks.controller.CRController.updateFormData(CRController.java:81)     在   com.cerner.docworks.controller.test.CRControllerTest.testUpdate(CRControllerTest.java:62)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)     在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     在java.lang.reflect.Method.invoke(Method.java:483)at   org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall(FrameworkMethod.java:50)     在   org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)     在   org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)     在   org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)     在   org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)     在org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)at   org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)     在   org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)     在org.junit.runners.ParentRunner $ 3.run(ParentRunner.java:290)at at   org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:71)at at   org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)at at   org.junit.runners.ParentRunner.access $ 000(ParentRunner.java:58)at at   org.junit.runners.ParentRunner $ 2.evaluate(ParentRunner.java:268)at at   org.junit.runners.ParentRunner.run(ParentRunner.java:363)at at   org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)     在   org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

FYI, CRDetails是一个带有

的pojo类
private String id;
    private String cr;
    private String desc;
    private CertificateGuidelines certGuidelines;
    private Date dueDate;
    //private String userType;
    private String solutionName;

FYI, 当我调试代码时,我发现mock将对象设置为null 如果我手动设置细节,测试用例通过,但我想使用mockito。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您需要使用MockitoJUnitRunner运行测试,例如:

@RunWith(MockitoJUnitRunner.class)
public class CRControllerTest {
     // ...

这样,@InjectMocks@Mock就可以正常使用。即mockView将创建为View的模拟,crController将使用相关的@Mock - 带注释的字段创建。

您可以参考the documentation了解如何注射鼹鼠。