0

I am getting null pointer exception at getSession(). Unable to write JUnit for it to mock the method. Kindly help on the same.

    public void updateData (List<Integer> cashFlows) {
        LOGGER.debug("Inside updateData method in ");
        LOGGER.debug("cashFlows Size " +cashFlows.size());
        try {
            String initialQuery = Constants.UPDATE_QUERY +cashFlows;
            initialQuery = initialQuery.replace("[", "(");
            initialQuery = initialQuery.replace("]", ")");
            LOGGER.debug("initialQuery: " + initialQuery);
            
            Query query = getSession().createNativeQuery(initialQuery);
            int updatedRows = query.executeUpdate();
            LOGGER.debug("Updated Rows : " + updatedRows);
        }
        catch(Exception e) {
            LOGGER.error("Error in updateData : " + e);
        }
    }

How could I write it's Junit as it is giving exception at getSession().createNativeQuery(initialQuery)

JUnit Code

@BeforeEach
 public void setUp() throws SQLException {
     when(getSession()).thenReturn(hibernateSession);
     
 }



 
 @Test
 public void updateDataTest()   {
     
     List<Integer> cashIdList=new ArrayList<Integer>();
     cashIdList.add(10);
     
     daoImpl.updateData(cashIdList);
     verify(tmsCfsCashflowsDaoImpl,times(1)).updateData(cashIdList);

 }   
  • If getSession() belongs to an instance, you should mock() that instance before stubbing the method with when(). If it's a static method instead, you should use mockStatic of power mockito – Matteo NNZ Aug 24 '22 at 07:23
  • Are you writing integration tests or unit tests. If it is unit test then you have to mock external dependencies. getSession() is one such thing – Akash tiwari Aug 24 '22 at 07:24
  • @Akashtiwari it is unit test could you help how could i mock that I am trying it from long not succeeding – Rupendra Singh Aug 24 '22 at 07:25
  • @MatteoNNZ how could I mock that it belongs to an instance. – Rupendra Singh Aug 24 '22 at 07:27
  • @RupendraSingh check this https://stackoverflow.com/questions/41583346/mocking-hibernate-session if it can help you – Akash tiwari Aug 24 '22 at 07:28
  • @Akashtiwari Tried this but it threw exception too , when passed like when(getSession()).thenReturn(hibernateSession); – Rupendra Singh Aug 24 '22 at 07:32
  • 2
    Who does getSession belongs to? If you navigate it, in which class do you end and what is the specific instance of that class that you are using in your test? That is what you should mock. Mocking is simply about Mockito.mock(YourClass.class), this returns an instance of YourClass, and that is the instance you have to use in your test and mock the methods calls on. – Matteo NNZ Aug 24 '22 at 08:02

0 Answers0