Skip to content

Commit

Permalink
add mock test
Browse files Browse the repository at this point in the history
  • Loading branch information
huyvu8051 committed Apr 20, 2024
1 parent 7b5e63b commit 1afdc54
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
6 changes: 6 additions & 0 deletions hicha-business/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<version>1.0.2</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package io.huyvu.hicha.hichabusiness.controller;

import com.github.javafaker.Faker;
import io.huyvu.hicha.hichabusiness.model.UserDTO;
import io.huyvu.hicha.hichabusiness.repository.UserRepository;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
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.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.IntStream;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


/**
* Mock test
*/
@WebMvcTest(HomeController.class)
@AutoConfigureMockMvc
@Slf4j
class HomeControllerTest {
@Autowired
MockMvc mockMvc;

@MockBean
UserRepository userRepository;

List<UserDTO> userDTOs = new ArrayList<>();
static Faker faker = new Faker(new Locale("vi"));

@BeforeEach
void setUp() {
IntStream.range(0, 10).forEach((e)->userDTOs.add(new UserDTO(null, faker.name().fullName())));

}

@SneakyThrows
@Test
void shouldFindAllUsers(){
when(userRepository.findAll()).thenReturn(userDTOs);

mockMvc.perform(get("/api/v1"))
.andExpect(status().isOk())
.andDo((result -> {
log.info(result.getResponse().getContentAsString(StandardCharsets.UTF_8));
}));
}
}

0 comments on commit 1afdc54

Please sign in to comment.