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.