Search code examples
javaspring-data-jpaspring-testspring-repositories

Null pointer Error when accessing JPARepository method in Spring data jpa


When I run this in test, NullPointerException occurs in the following line : Account acc = accRepo.findAccountById(Long id); As if the findAccountById(Long id) returns null. But when I call this method directly inside any other test method it works fine.

My Repository file

public Interface AccountRepo extends JpaRepository<Account,Long>{
    
    @Query("select a from Account a where a.id  = ?1")
    public List<Account> findAccountById(Long id);

}

Service Interface and Implementation

public Interface AccountService{
    Account showAcc();
}

@Service
public class AccServiceImpl implements AccountService {
    
    @Autowired
    private AccountRepo accRepo;

    @Override
    Account showAcc(){
        Long id = 10L;
        Account acc = accRepo.findAccountById(id); // Null Pointer exception at this line
        String name = acc.getName();
        System.out.println(name);
    }

}

@Autowired
AccountServiceimpl accServImpl;

@Test
public void testAccount(){
    
    accServImpl.showAcc();
}

Solution

  • You need to provide a AccountRepo for your AccServiceImpl in the test. The @Autowired annotation only works when you have a application context and is not the case for your test.

    So you'll need to add a setter or constructor in AccServiceImpl to provide the AccountRepo.

    If you want to test with the application context you'll need to implement a @SpringBootTest