-1

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();
}
Nandha
  • 192
  • 1
  • 2
  • 11

2 Answers2

2

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

Felipe Bonfante
  • 692
  • 5
  • 18
1

You have null pointer exception because AccountRepo is not getting autowired in your test case or actual setup if you are getting a NPE when running it outside context of a test framework. You need to check your test configurations and make sure that the accountrepo instance is created and injected by your test framework.

user2599052
  • 1,056
  • 3
  • 12
  • 27