Skip to content

Commit

Permalink
fix unit test for createUsers
Browse files Browse the repository at this point in the history
  • Loading branch information
letung999 committed Nov 23, 2023
1 parent f013f11 commit bccfa95
Showing 1 changed file with 55 additions and 5 deletions.
60 changes: 55 additions & 5 deletions src/test/java/com/ppn/ppn/service/UsersServiceTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.HashSet;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.*;

import static com.ppn.ppn.constant.ApprovalStatus.ACTIVE;
import static com.ppn.ppn.constant.ApprovalStatus.PENDING;
Expand Down Expand Up @@ -76,7 +76,7 @@ public void setup() {
public void givenUsersObject_whenCreateUsers_thenUsersObject() {

BDDMockito.given(usersRepository.findByEmail(usersDto.getEmail()))
.willReturn(Optional.of(users));
.willReturn(Optional.empty());
//action
BDDMockito.given(roleRepository.findByRoleName(VIEWER))
.willReturn(Optional.of(role));
Expand Down Expand Up @@ -149,6 +149,24 @@ public void givenUsersObjectHasNull_whenVerifyUser_thenThrowResourceNotFoundExce
BDDMockito.verify(usersRepository, BDDMockito.never()).save(any(Users.class));
}

@Test
public void givenUsersList_whenGetAll_thenUsersList() {
//setup
Page<Users> usersPage = BDDMockito.mock(Page.class);

Mockito.doReturn(getMockListUsers())
.when(usersPage).getContent();

BDDMockito.given(usersRepository.findAll(any(Pageable.class)))
.willReturn(usersPage);

//action
List<UsersDto> usersDtoList = usersService.all(PageRequest.of(0, 1));

//output
Assertions.assertThat(usersDtoList).isNotNull();
}

//private methods
private String randomString(int length) {
String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Expand All @@ -162,4 +180,36 @@ private String randomString(int length) {
}
return resultData.toString();
}

private List<Users> getMockListUsers() {
return List.of(
Users.builder()
.userId(1)
.email("[email protected]")
.firstName("tung")
.password(passwordEncoder.encode("123456"))
.phoneNumber("0338257409")
.status(String.valueOf(PENDING))
.roles(roles)
.build(),
Users.builder()
.userId(2)
.email("[email protected]")
.firstName("tung")
.password(passwordEncoder.encode("123456"))
.phoneNumber("0338257409")
.status(String.valueOf(PENDING))
.roles(roles)
.build(),
Users.builder()
.userId(3)
.email("[email protected]")
.firstName("tung")
.password(passwordEncoder.encode("123456"))
.phoneNumber("0338257409")
.status(String.valueOf(PENDING))
.roles(roles)
.build()
);
}
}

0 comments on commit bccfa95

Please sign in to comment.