英文:
how to write Junit test for exception scenarios when some data is not found in database
问题
我正在作为初级开发人员参与一个项目。我有非常少的经验。
我需要为getCompanyByUserId
方法编写单元测试,以处理USER_NOT_FOUND
和COMPANY_NOT_FOUND
异常情况。
这些异常在数据库中找不到userId
和companyId
时发生。
以下是代码片段:
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);
}
}
供您参考,以下是我编写的成功场景测试:
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);
}
您可以假设相关依赖项(如Junit、Mockito等)已添加。
英文:
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.
答案1
得分: 1
Sure, here's the translation:
"如果你不想手动使用之前的方法抛出异常,你需要模拟 UserRepository 并在调用 findUserByUserId 时返回空值。
when(userRepository.findUserByUserId(userId)).thenReturn(Optional.empty());
```"
<details>
<summary>英文:</summary>
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());
</details>
# 答案2
**得分**: 1
你需要在你的测试类中模拟`companyRepository`和`userRepository`。
我假设你的`getCompanyByUserId`方法在`CompanyService`类中。
```java
@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) {
// 在这里断言 COMPANY_NOT_FOUND
}
}
英文:
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
}
}
答案3
得分: 0
我相信这应该满足您的要求。您可能需要编写两个单独的测试用例来涵盖"用户未找到"和"公司未找到"两种情况。
用户未找到的测试用例:
@Test(expected = CompanyManagerException.class)
public void testGetCompanyShoukdThrowException(){
String userId = "UserId";
when(companyService.getCompanyByUserId(userId)).thenThrow(new CompanyManagerException("USER_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
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论