how to write Junit test for exception scenarios when some data is not found in database

Viewed 935

I'm working on a project as a junior developer. I have very little experience.

I need to write unit test for getCompanyByUserId for USER_NOT_FOUND and COMPANY_NOT_FOUND exception scenarios.

These exceptions occur when the userId and companyId are not found in the database.

The code snippets are as follows:

CompanyServiceImpl

 @Override
    public CompanyResponse getCompanyByUserId(String userId) {
        Optional<User> optionalUser = userRepository.findUserByUserId(userId);
        if(optionalUser.isEmpty()){
            throw new CompanyManagerException(USER_NOT_FOUND);
        }

        User user = optionalUser.get();

        Optional<Company> optionalCompany = companyRepository.findCompanyByCompanyName(user.getCompanyName());
        if(optionalCompany.isEmpty()){
            throw new CompanyManagerException(COMPANY_NOT_FOUND);
        }

For your reference, below is the test for success scenarios which I have written:

CompanyControllerTest

@Test
    public void testGetCompany() {
        String companyId = "companyId";

        when(companyService.getCompanyByUserId(companyId)).thenReturn(new CompanyResponse());

        ResponseEntity<CompanyResponse> response = companyController.getCompany(companyId);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getBody()).isInstanceOf(CompanyResponse.class);
}

You can assume that the related dependencies (Junit, Mockito, etc) are added.

3 Answers

you need to mock your UserRepository and return empty when findUserByUserId is called if you don't want to manually throw it with previous method

when(userRepository.findUserByUserId(userId)).thenReturn(Optional.empty());

You need to mock the companyRepository and userRepository in you Test class.

I am assuming your getCompanyByUserId is in CompanyService class

@Mock
private CompanyRepository companyRepository;

@Mock
private UserRepository userRepository;

@InjectMocks
private CompanyService service;

@Test
public void testGetCompanyByUserIdException() {
    Mockito.when(userRepository.findUserByUserId(Mockito.anyString())).thenReturn("");
    Mockito.when(companyRepository.findCompanyByCompanyName(Mockito.anyString())).thenReturn(null);
    try {
        service.getCompanyByUserId("");
    } catch(CompanyManagerException ex) {
    //assert here for COMPANY_NOT_FOUND
    }
}

I believe this should fulfil your requirement. You may have to write two separate test cases to cover both "user_not_found" and "company_not_found". Test case for User Not Found:

@Test(expected = CompanyManagerException.class)
public void testGetCompanyShoukdThrowException(){
String userId = "UserId";
when(companyService.getCompanyByUserId(userId)).thenThrow(new CompanyManagerException("USER_NOT_FOUND"));

//actual call and assert statements will go here

}
Related