From 7096f18cbd2cf71f08df1e23b9931be72cb047e0 Mon Sep 17 00:00:00 2001 From: LeTung <66472197+letung999@users.noreply.github.com> Date: Sun, 19 Nov 2023 23:15:37 +0700 Subject: [PATCH 1/2] Coverage unit test (#42) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * implement authentication and fix error security * refactor name version of dependencies * active prod environment * modify relationship entities to get data * add message status to response * turn on jpa auditing * add correlationId * handle verify email * override MethodArgumentNotValidException and handle exception * create role api * fix error verify email * remove redudant class * create a general for response api and modify response at controller * handle upload file amazon s3 * dÆhandle dÆÆownload file from s3 * implement redis server * implement search and advance search api * handle get ÃÃinformation company api * handle cache data for get all users * handle cache data search users api * add a field response data of CompanyProfile * add READ.ME for config send log from application to cloudWatch * set up monitoring log by CloudWatch * add document to set up cloudWatch * create update users api and invalidate cache * add payment class * modify relationship between CompanyProfile and CompanyProfileMapping * coverage unit tÃest for repository layer --------- Co-authored-by: letung999 --- .../repository/CompanyRepositoryTests.java | 88 ++++--------------- 1 file changed, 16 insertions(+), 72 deletions(-) diff --git a/src/test/java/com/ppn/ppn/repository/CompanyRepositoryTests.java b/src/test/java/com/ppn/ppn/repository/CompanyRepositoryTests.java index cb4556f..97bd49d 100644 --- a/src/test/java/com/ppn/ppn/repository/CompanyRepositoryTests.java +++ b/src/test/java/com/ppn/ppn/repository/CompanyRepositoryTests.java @@ -4,6 +4,7 @@ import com.ppn.ppn.entities.CompanyProfile; import com.ppn.ppn.entities.CompanyProfileMapping; import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; @@ -26,12 +27,15 @@ public class CompanyRepositoryTests { @Autowired private CompanyProfileMappingRepository companyProfileMappingRepository; - @Test - public void givenListCompanyProfile_whenGetListCompanyProfileByDate_thenListCompanyProfile() throws ParseException { - //setup - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date inputDate = simpleDateFormat.parse("2009-10-01"); - Date inputDate1 = simpleDateFormat.parse("2004-10-01"); + private SimpleDateFormat simpleDateFormat; + private Date inputDate; + private Date inputDate1; + + @BeforeEach + public void setup() throws ParseException { + simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); + inputDate = simpleDateFormat.parse("2009-10-01"); + inputDate1 = simpleDateFormat.parse("2004-10-01"); CompanyProfile companyProfile = CompanyProfile.builder() .companyIdName("001_shopBack") @@ -46,7 +50,6 @@ public void givenListCompanyProfile_whenGetListCompanyProfileByDate_thenListComp CompanyProfile companyProfileSaved = companyRepository.save(companyProfile); CompanyProfile companyProfileSaved1 = companyRepository.save(companyProfile1); - CompanyProfileMapping companyProfileMapping = CompanyProfileMapping.builder() .companyId(companyProfileSaved.getCompanyId()) .parentCompanyId("001_shopBack") @@ -60,6 +63,10 @@ public void givenListCompanyProfile_whenGetListCompanyProfileByDate_thenListComp companyProfileMappingRepository.save(companyProfileMapping); companyProfileMappingRepository.save(companyProfileMapping1); + } + + @Test + public void givenListCompanyProfile_whenGetListCompanyProfileByDate_thenListCompanyProfile() throws ParseException { //action List resultData = companyRepository.getListCompanyProfile(inputDate1); @@ -71,38 +78,7 @@ public void givenListCompanyProfile_whenGetListCompanyProfileByDate_thenListComp @Test public void givenListCompanyProfileId_whenGetListCompanyProfileId_thenListCompanyProfileId() throws ParseException { - //setup - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date inputDate = simpleDateFormat.parse("2009-10-01"); - Date inputDate1 = simpleDateFormat.parse("2004-10-01"); - - CompanyProfile companyProfile = CompanyProfile.builder() - .companyIdName("001_shopBack") - .dateOfEstablishment(inputDate) - .build(); - - CompanyProfile companyProfile1 = CompanyProfile.builder() - .companyIdName("002_ManHeim") - .dateOfEstablishment(inputDate1) - .build(); - - CompanyProfile companyProfileSaved = companyRepository.save(companyProfile); - CompanyProfile companyProfileSaved1 = companyRepository.save(companyProfile1); - - CompanyProfileMapping companyProfileMapping = CompanyProfileMapping.builder() - .companyId(companyProfileSaved.getCompanyId()) - .parentCompanyId("001_shopBack") - .companyProfile(companyProfileSaved) - .build(); - CompanyProfileMapping companyProfileMapping1 = CompanyProfileMapping.builder() - .companyId(companyProfileSaved1.getCompanyId()) - .parentCompanyId("002_ManHeim") - .companyProfile(companyProfileSaved1) - .build(); - - companyProfileMappingRepository.save(companyProfileMapping); - companyProfileMappingRepository.save(companyProfileMapping1); - + PageRequest pageRequest = PageRequest.of(0, 2); //action @@ -116,39 +92,7 @@ public void givenListCompanyProfileId_whenGetListCompanyProfileId_thenListCompan @Test public void givenListCompanyProfileIdIsEmpty_whenGetListCompanyProfileId_givenListCompanyProfileIdIsEmpty() throws ParseException { - //setup - //setup - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date inputDate = simpleDateFormat.parse("2009-10-01"); - Date inputDate1 = simpleDateFormat.parse("2004-10-01"); - - CompanyProfile companyProfile = CompanyProfile.builder() - .companyIdName("001_shopBack") - .dateOfEstablishment(inputDate) - .build(); - - CompanyProfile companyProfile1 = CompanyProfile.builder() - .companyIdName("002_ManHeim") - .dateOfEstablishment(inputDate1) - .build(); - - CompanyProfile companyProfileSaved = companyRepository.save(companyProfile); - CompanyProfile companyProfileSaved1 = companyRepository.save(companyProfile1); - - CompanyProfileMapping companyProfileMapping = CompanyProfileMapping.builder() - .companyId(companyProfileSaved.getCompanyId()) - .parentCompanyId("001_shopBack") - .companyProfile(companyProfileSaved) - .build(); - CompanyProfileMapping companyProfileMapping1 = CompanyProfileMapping.builder() - .companyId(companyProfileSaved1.getCompanyId()) - .parentCompanyId("002_ManHeim") - .companyProfile(companyProfileSaved1) - .build(); - - companyProfileMappingRepository.save(companyProfileMapping); - companyProfileMappingRepository.save(companyProfileMapping1); - + PageRequest pageRequest = PageRequest.of(1, 2); //action From edf76f5d68ddb13c83659779d3beee72002ed977 Mon Sep 17 00:00:00 2001 From: LeTung <66472197+letung999@users.noreply.github.com> Date: Tue, 21 Nov 2023 10:59:59 +0700 Subject: [PATCH 2/2] coverage unit test for userservice (#43) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * implement authentication and fix error security * refactor name version of dependencies * active prod environment * modify relationship entities to get data * add message status to response * turn on jpa auditing * add correlationId * handle verify email * override MethodArgumentNotValidException and handle exception * create role api * fix error verify email * remove redudant class * create a general for response api and modify response at controller * handle upload file amazon s3 * dÆhandle dÆÆownload file from s3 * implement redis server * implement search and advance search api * handle get ÃÃinformation company api * handle cache data for get all users * handle cache data search users api * add a field response data of CompanyProfile * add READ.ME for config send log from application to cloudWatch * set up monitoring log by CloudWatch * add document to set up cloudWatch * create update users api and invalidate cache * add payment class * modify relationship between CompanyProfile and CompanyProfileMapping * coverage unit tÃest for repository layer * add builder anotation of lombok * unit test for usersService --------- Co-authored-by: letung999 --- src/main/java/com/ppn/ppn/dto/UsersDto.java | 6 +- src/main/java/com/ppn/ppn/entities/Role.java | 6 +- .../ppn/repository/RoleRepositoryTests.java | 63 +++++++ .../ppn/ppn/service/UsersServiceTests.java | 165 ++++++++++++++++++ 4 files changed, 236 insertions(+), 4 deletions(-) create mode 100644 src/test/java/com/ppn/ppn/repository/RoleRepositoryTests.java create mode 100644 src/test/java/com/ppn/ppn/service/UsersServiceTests.java diff --git a/src/main/java/com/ppn/ppn/dto/UsersDto.java b/src/main/java/com/ppn/ppn/dto/UsersDto.java index 3c61ea5..c33441b 100644 --- a/src/main/java/com/ppn/ppn/dto/UsersDto.java +++ b/src/main/java/com/ppn/ppn/dto/UsersDto.java @@ -4,14 +4,16 @@ import com.ppn.ppn.entities.Payment; import com.ppn.ppn.entities.Role; import jakarta.validation.constraints.NotBlank; -import lombok.Getter; -import lombok.Setter; +import lombok.*; import java.util.List; import java.util.Set; @Getter @Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor public class UsersDto extends BaseEntityDto { private Integer userId; diff --git a/src/main/java/com/ppn/ppn/entities/Role.java b/src/main/java/com/ppn/ppn/entities/Role.java index 7acb067..797fb01 100644 --- a/src/main/java/com/ppn/ppn/entities/Role.java +++ b/src/main/java/com/ppn/ppn/entities/Role.java @@ -2,8 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.*; -import lombok.Getter; -import lombok.Setter; +import lombok.*; import java.util.Set; @@ -11,6 +10,9 @@ @Entity @Getter @Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor public class Role extends BaseEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/src/test/java/com/ppn/ppn/repository/RoleRepositoryTests.java b/src/test/java/com/ppn/ppn/repository/RoleRepositoryTests.java new file mode 100644 index 0000000..68eaa42 --- /dev/null +++ b/src/test/java/com/ppn/ppn/repository/RoleRepositoryTests.java @@ -0,0 +1,63 @@ +package com.ppn.ppn.repository; + + +import com.ppn.ppn.entities.Role; +import com.ppn.ppn.entities.Users; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; + +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; + +import static com.ppn.ppn.constant.RoleConstant.VIEWER; + +@DataJpaTest +@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +public class RoleRepositoryTests { + + @Autowired + private RoleRepository roleRepository; + + @Autowired + private UsersRepository usersRepository; + + @BeforeEach + public void setup() { + //setup + Users users = Users.builder() + .email("letung012000@gmail.com") + .firstName("tung") + .phoneNumber("0338257409") + .password("123456") + .status("PENDING") + .gender("Male") + .build(); + Users dataSave = usersRepository.save(users); + + Set usersSet = new HashSet<>(); + usersSet.add(dataSave); + + Role role = Role.builder() + .roleName(VIEWER) + .users(usersSet) + .build(); + + roleRepository.save(role); + } + + @Test + public void givenRoleObject_whenFindByRoleName_thenRoleObject() { + + //action + Optional role = roleRepository.findByRoleName(VIEWER); + + //output + Assertions.assertThat(role).isNotNull(); + Assertions.assertThat(role.get().getRoleName()).isEqualTo(VIEWER); + } +} diff --git a/src/test/java/com/ppn/ppn/service/UsersServiceTests.java b/src/test/java/com/ppn/ppn/service/UsersServiceTests.java new file mode 100644 index 0000000..61d1fd1 --- /dev/null +++ b/src/test/java/com/ppn/ppn/service/UsersServiceTests.java @@ -0,0 +1,165 @@ +package com.ppn.ppn.service; + + +import com.ppn.ppn.dto.UsersDto; +import com.ppn.ppn.entities.Role; +import com.ppn.ppn.entities.Users; +import com.ppn.ppn.exception.ResourceDuplicateException; +import com.ppn.ppn.exception.ResourcesNotFoundException; +import com.ppn.ppn.mapper.UsersMapper; +import com.ppn.ppn.repository.RoleRepository; +import com.ppn.ppn.repository.UsersRepository; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.*; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.crypto.password.PasswordEncoder; + +import java.util.HashSet; +import java.util.Optional; +import java.util.Random; +import java.util.Set; + +import static com.ppn.ppn.constant.ApprovalStatus.ACTIVE; +import static com.ppn.ppn.constant.ApprovalStatus.PENDING; +import static com.ppn.ppn.constant.RoleConstant.VIEWER; +import static org.mockito.ArgumentMatchers.any; + +@ExtendWith(MockitoExtension.class) +public class UsersServiceTests { + + @Mock + private UsersRepository usersRepository; + @Mock + private RoleRepository roleRepository; + @InjectMocks + private UsersServiceImpl usersService; + @Spy + private UsersMapper usersMapper = UsersMapper.INSTANCE; + @Mock + private PasswordEncoder passwordEncoder; + + private Users users; + private Role role; + private UsersDto usersDto; + private Set roles = new HashSet<>(); + + @BeforeEach + public void setup() { + + role = Role.builder() + .roleId(1) + .roleName(VIEWER) + .build(); + roles.add(role); + + usersDto = UsersDto.builder() + .userId(1) + .email("letung012000@gmail.com") + .firstName("tung") + .password(passwordEncoder.encode("123456")) + .phoneNumber("0338257409") + .status(String.valueOf(PENDING)) + .roles(roles) + .build(); + users = usersMapper.usersDtoUsers(usersDto); + + users.setStatus(String.valueOf(PENDING)); + users.setVerifyCode(randomString(30)); + users.setPassword(passwordEncoder.encode(usersDto.getPassword())); + users.setRoles(roles); + } + + @Test + public void givenUsersObject_whenCreateUsers_thenUsersObject() { + + BDDMockito.given(usersRepository.findByEmail(usersDto.getEmail())) + .willReturn(Optional.of(users)); + //action + BDDMockito.given(roleRepository.findByRoleName(VIEWER)) + .willReturn(Optional.of(role)); + + BDDMockito.when(usersRepository.save(any())).thenReturn(users); + + UsersDto dataSave = usersService.createUsers(usersMapper.usersToUsersDto(users)); + + //output + Assertions.assertThat(dataSave).isNotNull(); + } + + @Test + public void givenExistingEmail_whenCreateUsers_thenThrowResourceDuplicateException() { + //action + BDDMockito.given(usersRepository.findByEmail(usersDto.getEmail())) + .willReturn(Optional.of(users)); + //output + org.junit.jupiter.api.Assertions.assertThrows(ResourceDuplicateException.class, () -> { + usersService.createUsers(usersDto); + }); + + BDDMockito.verify(roleRepository, Mockito.never()).findByRoleName(VIEWER); + BDDMockito.verify(usersRepository, Mockito.never()).save(any()); + } + + @Test + public void givenRoleHasNull_whenCreateUsers_thenThrowResourceNotFoundException() { + //action + BDDMockito.given(usersRepository.findByEmail(usersDto.getEmail())) + .willReturn(Optional.empty()); + + BDDMockito.given(roleRepository.findByRoleName(VIEWER)) + .willReturn(Optional.empty()); + //output + org.junit.jupiter.api.Assertions.assertThrows(ResourcesNotFoundException.class, () -> { + usersService.createUsers(usersDto); + }); + + BDDMockito.verify(usersRepository, Mockito.never()).save(any(Users.class)); + } + + @Test + public void givenUsersObjectModified_whenVerifyUser_thenReturnTrue() { + //setup + BDDMockito.given(usersRepository.findByVerifyCode(users.getVerifyCode())) + .willReturn(Optional.of(users)); + //action + users.setStatus(String.valueOf(ACTIVE)); + + BDDMockito.given(usersRepository.save(any(Users.class))).willReturn(users); + + Boolean result = usersService.verifyUser(users.getVerifyCode()); + + //output + Assertions.assertThat(result).isEqualTo(true); + } + + @Test + public void givenUsersObjectHasNull_whenVerifyUser_thenThrowResourceNotFoundException() { + //setup + BDDMockito.given(usersRepository.findByVerifyCode(users.getVerifyCode())) + .willReturn(Optional.empty()); + + //output + org.junit.jupiter.api.Assertions.assertThrows(ResourcesNotFoundException.class, () -> { + usersService.verifyUser(users.getVerifyCode()); + }); + + BDDMockito.verify(usersRepository, BDDMockito.never()).save(any(Users.class)); + } + + //private methods + private String randomString(int length) { + String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + "0123456789" + + "abcdefghijklmnopqrstuvxyz"; + Random random = new Random(); + StringBuilder resultData = new StringBuilder(); + for (int i = 0; i < length; ++i) { + int index = random.nextInt(data.length()) + 0; + resultData.append(data.charAt(index)); + } + return resultData.toString(); + } +}