如何编写 Junit 测试以处理在数据库中找不到某些数据时的异常情况。

huangapple go评论156阅读模式
英文:

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

问题

我正在作为初级开发人员参与一个项目。我有非常少的经验。

我需要为getCompanyByUserId方法编写单元测试,以处理USER_NOT_FOUNDCOMPANY_NOT_FOUND异常情况。

这些异常在数据库中找不到userIdcompanyId时发生。

以下是代码片段:

CompanyServiceImpl

  1. @Override
  2. public CompanyResponse getCompanyByUserId(String userId) {
  3. Optional<User> optionalUser = userRepository.findUserByUserId(userId);
  4. if (optionalUser.isEmpty()) {
  5. throw new CompanyManagerException(USER_NOT_FOUND);
  6. }
  7. User user = optionalUser.get();
  8. Optional<Company> optionalCompany = companyRepository.findCompanyByCompanyName(user.getCompanyName());
  9. if (optionalCompany.isEmpty()) {
  10. throw new CompanyManagerException(COMPANY_NOT_FOUND);
  11. }
  12. }

供您参考,以下是我编写的成功场景测试:

CompanyControllerTest

  1. @Test
  2. public void testGetCompany() {
  3. String companyId = "companyId";
  4. when(companyService.getCompanyByUserId(companyId)).thenReturn(new CompanyResponse());
  5. ResponseEntity<CompanyResponse> response = companyController.getCompany(companyId);
  6. assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
  7. assertThat(response.getBody()).isInstanceOf(CompanyResponse.class);
  8. }

您可以假设相关依赖项(如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

  1. @Override
  2. public CompanyResponse getCompanyByUserId(String userId) {
  3. Optional&lt;User&gt; optionalUser = userRepository.findUserByUserId(userId);
  4. if(optionalUser.isEmpty()){
  5. throw new CompanyManagerException(USER_NOT_FOUND);
  6. }
  7. User user = optionalUser.get();
  8. Optional&lt;Company&gt; optionalCompany = companyRepository.findCompanyByCompanyName(user.getCompanyName());
  9. if(optionalCompany.isEmpty()){
  10. throw new CompanyManagerException(COMPANY_NOT_FOUND);
  11. }

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

CompanyControllerTest

  1. @Test
  2. public void testGetCompany() {
  3. String companyId = &quot;companyId&quot;;
  4. when(companyService.getCompanyByUserId(companyId)).thenReturn(new CompanyResponse());
  5. ResponseEntity&lt;CompanyResponse&gt; response = companyController.getCompany(companyId);
  6. assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
  7. assertThat(response.getBody()).isInstanceOf(CompanyResponse.class);
  8. }

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

答案1

得分: 1

Sure, here's the translation:

"如果你不想手动使用之前的方法抛出异常,你需要模拟 UserRepository 并在调用 findUserByUserId 时返回空值。

  1. when(userRepository.findUserByUserId(userId)).thenReturn(Optional.empty());
  2. ```"
  3. <details>
  4. <summary>英文:</summary>
  5. you need to mock your UserRepository and return empty when findUserByUserId is called if you don&#39;t want to manually throw it with previous method
  6. when(userRepository.findUserByUserId(userId)).thenReturn(Optional.empty());
  7. </details>
  8. # 答案2
  9. **得分**: 1
  10. 你需要在你的测试类中模拟`companyRepository`和`userRepository`。
  11. 我假设你的`getCompanyByUserId`方法在`CompanyService`类中。
  12. ```java
  13. @Mock
  14. private CompanyRepository companyRepository;
  15. @Mock
  16. private UserRepository userRepository;
  17. @InjectMocks
  18. private CompanyService service;
  19. @Test
  20. public void testGetCompanyByUserIdException() {
  21. Mockito.when(userRepository.findUserByUserId(Mockito.anyString())).thenReturn("");
  22. Mockito.when(companyRepository.findCompanyByCompanyName(Mockito.anyString())).thenReturn(null);
  23. try {
  24. service.getCompanyByUserId("");
  25. } catch(CompanyManagerException ex) {
  26. // 在这里断言 COMPANY_NOT_FOUND
  27. }
  28. }
英文:

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

I am assuming your getCompanyByUserId is in CompanyService class

  1. @Mock
  2. private CompanyRepository companyRepository;
  3. @Mock
  4. private UserRepository userRepository;
  5. @InjectMocks
  6. private CompanyService service;
  7. @Test
  8. public void testGetCompanyByUserIdException() {
  9. Mockito.when(userRepository.findUserByUserId(Mockito.anyString())).thenReturn(&quot;&quot;);
  10. Mockito.when(companyRepository.findCompanyByCompanyName(Mockito.anyString())).thenReturn(null);
  11. try {
  12. service.getCompanyByUserId(&quot;&quot;);
  13. } catch(CompanyManagerException ex) {
  14. //assert here for COMPANY_NOT_FOUND
  15. }
  16. }

答案3

得分: 0

我相信这应该满足您的要求。您可能需要编写两个单独的测试用例来涵盖"用户未找到"和"公司未找到"两种情况。
用户未找到的测试用例:

  1. @Test(expected = CompanyManagerException.class)
  2. public void testGetCompanyShoukdThrowException(){
  3. String userId = "UserId";
  4. when(companyService.getCompanyByUserId(userId)).thenThrow(new CompanyManagerException("USER_NOT_FOUND"));
  5. //实际调用和断言语句将在这里进行
  6. }
英文:

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:

  1. @Test(expected = CompanyManagerException.class)
  2. public void testGetCompanyShoukdThrowException(){
  3. String userId = &quot;UserId&quot;;
  4. when(companyService.getCompanyByUserId(userId)).thenThrow(new CompanyManagerException(&quot;USER_NOT_FOUND&quot;));
  5. //actual call and assert statements will go here
  6. }
  7. </details>

huangapple
  • 本文由 发表于 2020年8月12日 16:52:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63373091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定