2016-12-06 3 views
1

Я использую Mockito для тестирования. Получение nullpointerexcpetion с сообщением утратившимИсключение исключения нулевой указатель при использовании mockito

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 = "[email protected]"; 
    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); 
     } 

}` 

Я получаю nuppointerexception на линии updateQuery.setParameter(Constants.ACCOUNTID,UUID.fromString(requestObject.getAccountId().toUpperCase())).

Я могу видеть, что идентификатор аккаунта доступен в requestObject при отладке. Ниже приведен стек. Помощь в apprecited :)

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

Ваш раскорчевка из session.createQuery:
when(session.createQuery(SQLConstants.FETCH_PERSON_ACCT)).thenReturn(query);

И то, что ваш код на самом деле вызывает прямо прежде чем вы получите исключение:
Query updateQuery = session.createQuery(SQLConstants.UPDATE_PERSON_ACCOUNT);

Так CreateQuery является затушил для возврата запроса при вызове с другой константой. Значение вашего производственного кода вернет null из createQuery, а следующая строка затем выбросит ваш NPE.

+0

Perfect. Я добавил, когда (session.createQuery (SQLConstants.UPDATE_PERSON_ACCOUNT)). ThenReturn (query); иметь константу для updatePerson. Это сработало. Благодаря! @hagbard – arjun

Смежные вопросы