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

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

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

问题

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

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

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

以下是代码片段:

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&lt;User&gt; optionalUser = userRepository.findUserByUserId(userId);
        if(optionalUser.isEmpty()){
            throw new CompanyManagerException(USER_NOT_FOUND);
        }

        User user = optionalUser.get();

        Optional&lt;Company&gt; 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 = &quot;companyId&quot;;

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

        ResponseEntity&lt;CompanyResponse&gt; 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&#39;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(&quot;&quot;);
	Mockito.when(companyRepository.findCompanyByCompanyName(Mockito.anyString())).thenReturn(null);
	try {
		service.getCompanyByUserId(&quot;&quot;);
	} 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 = &quot;UserId&quot;;
when(companyService.getCompanyByUserId(userId)).thenThrow(new CompanyManagerException(&quot;USER_NOT_FOUND&quot;));

//actual call and assert statements will go here

}

</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:

确定