使用mockito时面临空指针异常

时间:2016-12-06 23:09:36

标签: junit nullpointerexception null mockito

我正在使用Mockito进行测试。获取nullpointerexcpetion,消息为null

TestMethod的

  // build request
     RequestObject requestObject = new RequestObject();

     String accountNumber = "12345628928";
     String accountId = "dc23362e-f46f-4cce-b49a-cd10d737f483";

     requestObject.setAccountId(accountId);
     requestObject.setAccountNumber(accountNumber);

     String firstName = "test";
     String middlename = "test";
     String lastName = "test";
     String gender = "M";
     String dob = "01-JUN-2016";         
     String emailaddress = "test@test.com";
     String prefferedLanguageCode = "1";
     String preffredname = "test";
     String prefix = "Mr.";
     String suffix = "Jr";
     String minor = "1";
     String deathDate = "09-SEP-2009";
     String deathInformationDate = "14-OCT-2010";

     Customer customer = new Customer();

     customer.setFirstName(firstName);
     customer.setMiddleName(middlename);
     customer.setLastName(lastName);
     customer.setGender(gender);
     customer.setDob(dob);
     customer.setEmail(emailaddress);        
     customer.setPreferredLanguageCode(prefferedLanguageCode);
     customer.setPreferredName(preffredname);
     customer.setPrefix(prefix);
     customer.setSuffix(suffix);       
     customer.setMinor(minor);
     customer.setDeathDate(deathDate);
     customer.setDeathInformedDate(deathInformationDate);

     requestObject.setCustomer(customer);

     IdObject idObject = new IdObject();     
     idObject.setAccountId(UUID.fromString(accountId)); 

     List<PersonAccount> personAccount = new ArrayList<PersonAccount>();

     PersonAccount personAccount1 = new PersonAccount();
     personAccount1.setFirstName("First name in testing");

     personAccount.add(personAccount1);

     // mock external call
     when(sessionFactory.openSession()).thenReturn(session);
     when(session.beginTransaction()).thenReturn(transaction);              
       when(session.createQuery(SQLConstants.FETCH_PERSON_ACCT)).thenReturn(query);
     when(query.list()).thenReturn(personAccount);
     when(query.executeUpdate()).thenReturn(1);

     // Call the testing method
     idObject = customerDAOImpl.updateCustomerRecord(requestObject); 

     //check the assertion
     assertEquals("dc23362e-f46f-4cce-b49a-cd10d737f483", idObject.getAccountId().toString());

    // verify the mock call
    verify(customerDAOImpl, times(1)).updateCustomerRecord(requestObject);

和我的 UpdateMethod `

private void updateAccountInformation(RequestObject requestObject, Session session) 
            throws CustomerDataException{

          try{
         Query queryForPersonAccount = session.createQuery(SQLConstants.FETCH_PERSON_ACCT);
         queryForPersonAccount.setParameter(Constants.ACCOUNTID, UUID.fromString(requestObject.getAccountId().toUpperCase()));


          @SuppressWarnings("unchecked")
         List<PersonAccount> listpersonAccount = (List<PersonAccount>) queryForPersonAccount.list();

                 if (CollectionUtils.isNotEmpty(listpersonAccount)) {   

                     PersonAccount personAccount = listpersonAccount.get(0);

                 Query updateQuery = session.createQuery(SQLConstants.UPDATE_PERSON_ACCOUNT);
                 updateQuery.setParameter(Constants.ACCOUNTID,UUID.fromString(requestObject.getAccountId().toUpperCase()));              
                 updateQuery.setParameter(Constants.UPDATED_BY_NAME, Constants.PCF);
                 updateQuery.setParameter(Constants.END_TIMESTAMP,DateUtil.dateDDMMMYY());                    

                 updateQuery.executeUpdate();

                 updatePersonAccount(session,personAccount, requestObject);


                 }else{
                     throw new CustomerDataException(MessageKeys.UPDATE_CUSTOMER_ERRROR_MESSAGE);
                 }
      }catch(Exception ex)
      {
          LOGGER.error(Constants.PATIENT_FETCH_EXCEPTION, ex);
           throw new CustomerDataException(MessageKeys.UPDATE_CUSTOMER_ERRROR_MESSAGE);
      }

}`

我在第updateQuery.setParameter(Constants.ACCOUNTID,UUID.fromString(requestObject.getAccountId().toUpperCase()))行获得了nuppointerexception。

我可以在调试时看到accountID在requestObject中可用。 以下是堆栈跟踪。帮助很感激:)

ava.lang.NullPointerException: null
at com.cardinalhealth.chh.dao.CustomerDAOImpl.updateAccountInformation(CustomerDAOImpl.java:312)
at com.cardinalhealth.chh.dao.CustomerDAOImpl.updateCustomer(CustomerDAOImpl.java:285)
at com.cardinalhealth.chh.dao.CustomerDAOImpl.updateCustomerInformations(CustomerDAOImpl.java:180)
at com.cardinalhealth.chh.dao.CustomerDAOImpl.updateCustomerRecord(CustomerDAOImpl.java:141)
at com.cardinalhealth.chh.dao.CustomerDAOImplTest.testUpdateCustomerRecordforCustomerObject(CustomerDAOImplTest.java:452)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

1 个答案:

答案 0 :(得分:1)

你对session.createQuery的存根:
when(session.createQuery(SQLConstants.FETCH_PERSON_ACCT)).thenReturn(query);

在获得例外之前,您的代码实际调用了什么:
Query updateQuery = session.createQuery(SQLConstants.UPDATE_PERSON_ACCOUNT);

因此,createQuery被存根以在使用不同的常量调用时返回查询。 这意味着您的生产代码将从createQuery返回null,然后下一行将抛出您的NPE。