Skip to content

Commit

Permalink
Create test for VideoServiceImpl
Browse files Browse the repository at this point in the history
  • Loading branch information
LauroSilveira committed Dec 20, 2023
1 parent c4025db commit dcd7c7d
Show file tree
Hide file tree
Showing 10 changed files with 244 additions and 22 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.11</version>
<configuration>
<excludes>com/appzara/entity/**</excludes>
<excludes>com.alura.aluraflixapi.domain/**</excludes>
</configuration>
<executions>
<execution>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -24,7 +23,7 @@
@RequestMapping("/category")
@SecurityRequirement(name = "bearer-key")
public class CategoryController {
private static final String PREFIX_LOGGIN = "CategoryController";
private static final String PREFIX_LOGGING = "CategoryController";

private final CategoryService categoryService;

Expand All @@ -34,33 +33,33 @@ public CategoryController(CategoryService categoryService) {

@GetMapping(produces = "application/json")
public ResponseEntity<List<CategoryDto>> categories() {
log.info("{} Request to retrieve all Categories", PREFIX_LOGGIN);
log.info("{} Request to retrieve all Categories", PREFIX_LOGGING);
List<CategoryDto> categories = categoryService.categories();
return ResponseEntity.ok(categories);
}

@PostMapping(produces = "application/json", consumes = "application/json")
public ResponseEntity<CategoryDto> create(@RequestBody @Valid final CategoryDto categoryDto) {
categoryService.create(categoryDto);
log.info("{} Request to create a new Category", PREFIX_LOGGIN);
log.info("{} Request to create a new Category", PREFIX_LOGGING);
return ResponseEntity.ok(categoryDto);
}

@GetMapping(value = "/{id}", produces = "application/json")
public ResponseEntity<CategoryDto> findCategoryById(@NotBlank @PathVariable final String id) {
log.info("{} Request to get a Category with Id: {}", PREFIX_LOGGIN, id);
log.info("{} Request to get a Category with Id: {}", PREFIX_LOGGING, id);
final var category = this.categoryService.findCategoryById(id);
return ResponseEntity.status(HttpStatus.FOUND).body(category);

}

@GetMapping(value = "/{id}/videos", produces = "application/json")
@GetMapping(value = "/{rating}/videos", produces = "application/json")
public ResponseEntity<List<VideoDto>> getVideosByCategory(
@NotBlank @PathVariable final String id) {
log.info("{} Request to search a Video by Category with Id: {}", PREFIX_LOGGIN, id);
final var response = this.categoryService.getVideosByCategory(id);
@NotBlank @PathVariable final String rating) {
log.info("{} Request to search a Video by Category with Id: {}", PREFIX_LOGGING, rating);
final var response = this.categoryService.getVideosByCategory(rating);
if (response.isEmpty()) {
log.info("{} Response: {}", PREFIX_LOGGIN, response);
log.info("{} Response: {}", PREFIX_LOGGING, response);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
} else {
return ResponseEntity.status(HttpStatus.FOUND).body(response);
Expand All @@ -69,7 +68,7 @@ public ResponseEntity<List<VideoDto>> getVideosByCategory(

@DeleteMapping(value = "/{id}", produces = "application/json")
public ResponseEntity<HttpStatus> deleteCategory(@NotBlank @PathVariable final String id) {
log.info("{} Request to Delete Category with Id: {}", PREFIX_LOGGIN, id);
log.info("{} Request to Delete Category with Id: {}", PREFIX_LOGGING, id);
final var response = this.categoryService.deleteCategory(id);
return ResponseEntity.status(response).build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ public interface CategoryService {

HttpStatus deleteCategory(String id);

List<VideoDto> getVideosByCategory(String id);
List<VideoDto> getVideosByCategory(String rating);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
package com.alura.aluraflixapi.controller;

import com.alura.aluraflixapi.domain.category.dto.CategoryDto;
import com.alura.aluraflixapi.domain.video.dto.VideoDto;
import com.alura.aluraflixapi.infraestructure.repository.UserRepository;
import com.alura.aluraflixapi.infraestructure.security.TokenService;
import com.alura.aluraflixapi.infraestructure.service.CategoryService;
import com.alura.aluraflixapi.infraestructure.service.UserService;
import com.alura.aluraflixapi.infraestructure.service.VideoService;
import com.alura.aluraflixapi.jsonutils.ParseJson;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import java.util.Arrays;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@ExtendWith(SpringExtension.class)
//@WebMvcTest: Includes both the @AutoConfigureWebMvc and the @AutoConfigureMockMvc, among other functionality.
@WebMvcTest
//this annotation can be replaced at each test method scope
@WithMockUser(value = "admin", username = "admin", password = "admin", roles = "ADMIN")
class CategoryControllerTest extends ParseJson {

private static final String PREFIX_PATH = "/category/";

private static ObjectMapper mapper;

@Autowired
private MockMvc mockMvc;

@MockBean
private CategoryService categoryService;

@MockBean
private AuthenticationController authenticationController;

@MockBean
private UserService userService;

@MockBean
private VideoService videoService;

@MockBean
private TokenService tokenService;

@MockBean
private UserRepository userRepository;


@BeforeEach
void setup() {
mapper = new ObjectMapper();
}

@Test
@DisplayName("Should return all Categories and response OK")
void categories_test() throws Exception {
//Given
final var jsonFile = getJsonFile(PREFIX_PATH + "getAllCategories_response_ok.json");
final var categoriesDtoExpected = Arrays.stream(parseToJavaObject(jsonFile, CategoryDto[].class)).toList();
when(this.categoryService.categories())
.thenReturn(categoriesDtoExpected);
//When
final var response = this.mockMvc.perform(MockMvcRequestBuilders.get("/category")
.accept(MediaType.APPLICATION_JSON)
).andDo(MockMvcResultHandlers.print())
.andExpect(status().is2xxSuccessful())
.andReturn();

//Then
assertThat(response).isNotNull();
final var categoriesResponse = mapper.readValue(response.getResponse().getContentAsString(), new TypeReference<List<CategoryDto>>() {
});
assertThat(categoriesDtoExpected).usingRecursiveComparison().isEqualTo(categoriesResponse);
}

@Test
@DisplayName("Should create a new category and response OK")
void create_test() throws Exception {
//Given
final var jsonFile = getJsonFile(PREFIX_PATH + "create_category_response_ok.json");
final var categoriesDtoExpected = parseToJavaObject(jsonFile, CategoryDto.class);
when(this.categoryService.create(any()))
.thenReturn(categoriesDtoExpected);
//When
final var response = this.mockMvc.perform(MockMvcRequestBuilders.post("/category")
.with(SecurityMockMvcRequestPostProcessors.csrf().asHeader())
.content(mapper.writeValueAsBytes(categoriesDtoExpected))
.contentType(MediaType.APPLICATION_JSON)
).andDo(MockMvcResultHandlers.print())
.andExpect(status().is2xxSuccessful())
.andReturn();

//Then
assertThat(response).isNotNull();
final var categoriesResponse = mapper.readValue(response.getResponse().getContentAsString(), new TypeReference<CategoryDto>() {
});
assertThat(categoriesDtoExpected).usingRecursiveComparison().isEqualTo(categoriesResponse);
}

@Test
@DisplayName("Should find a category by Id and response OK")
void findCategoryById_test() throws Exception {
//Given
final var jsonFile = getJsonFile(PREFIX_PATH + "findCategoryById_response_ok.json");
final var categoriesDtoExpected = parseToJavaObject(jsonFile, CategoryDto.class);
when(this.categoryService.findCategoryById(anyString()))
.thenReturn(categoriesDtoExpected);
//When
final var response = this.mockMvc.perform(MockMvcRequestBuilders.get("/category/{id}", "63f67ec16295ed744dd460cd")
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print())
.andExpect(status().is3xxRedirection())
.andReturn();

//Then
assertThat(response).isNotNull();
final var categoriesResponse = mapper.readValue(response.getResponse().getContentAsString(), new TypeReference<CategoryDto>() {
});
assertThat(categoriesDtoExpected).usingRecursiveComparison().isEqualTo(categoriesResponse);
}

@Test
@DisplayName("Should return a video by category Id and response OK")
void getVideosByCategory_test() throws Exception {
//Given
final var jsonFile = getJsonFile(PREFIX_PATH + "getVideosByCategory_response_ok.json");
final var categoriesDtoExpected = Arrays.stream(parseToJavaObject(jsonFile, VideoDto[].class)).toList();
when(this.categoryService.getVideosByCategory(anyString()))
.thenReturn(categoriesDtoExpected);
//When
final var response = this.mockMvc.perform(MockMvcRequestBuilders.get("/category/{rating}/videos", "FREE")
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print())
.andExpect(status().is3xxRedirection())
.andReturn();

//Then
assertThat(response).isNotNull();
final var categoriesResponse = mapper.readValue(response.getResponse().getContentAsString(), new TypeReference<List<VideoDto>>() {
});
assertThat(categoriesDtoExpected).usingRecursiveComparison().isEqualTo(categoriesResponse);
}

@Test
void deleteCategory_test() throws Exception {
//Given
when(this.categoryService.deleteCategory(anyString())).thenReturn(HttpStatus.ACCEPTED);
//The
this.mockMvc.perform(MockMvcRequestBuilders.delete("/category/{id}", "63f67ec16295ed744dd460cd")
.with(SecurityMockMvcRequestPostProcessors.csrf().asHeader())
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isAccepted());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
@ExtendWith(SpringExtension.class)
class VideoServiceImplTest extends ParseJson {

private static final String PREFIX_PATH = "/video/";

@MockBean
private VideoRepository videoRepository;
@SpyBean
Expand All @@ -39,7 +41,7 @@ class VideoServiceImplTest extends ParseJson {
@Test
void getVideos_response_ok_test() {
//Given
final var jsonFile = getJsonFile("getAllVideos_response_ok.json");
final var jsonFile = getJsonFile(PREFIX_PATH + "getAllVideos_response_ok.json");
final var videos = parseToJavaObject(jsonFile, Video[].class);
final Page<Video> pagesVideos = new PageImpl<>(Arrays.stream(videos).toList());

Expand All @@ -58,7 +60,7 @@ void getVideos_response_ok_test() {
@Test
void save_response_ok_test() {
//Given
final var jsonFile = getJsonFile("create_video_response_ok.json");
final var jsonFile = getJsonFile(PREFIX_PATH + "create_video_response_ok.json");
final var videoDto = parseToJavaObject(jsonFile, VideoDto.class);
final var videoModel = this.videoMapper.mapToModel(videoDto);
when(this.videoMapper.mapToModel(any(VideoDto.class))).thenReturn(videoModel);
Expand All @@ -76,7 +78,7 @@ void save_response_ok_test() {
void updateMovie_response_ok_test() {

//Given
final var jsonFile = getJsonFile("update_video_response_ok.json");
final var jsonFile = getJsonFile(PREFIX_PATH + "update_video_response_ok.json");
final var updateVideoDtoParsed = parseToJavaObject(jsonFile, UpdateVideoDto.class);
final var model = this.videoMapper.mapToModel(updateVideoDtoParsed);
final var updateVideoDto = this.videoMapper.mapToUpdateVideoDto(model);
Expand All @@ -94,7 +96,7 @@ void updateMovie_response_ok_test() {
@Test
void delete_response_ok_test() {
//Given
final var jsonFile = getJsonFile("delete_video_response_ok.json");
final var jsonFile = getJsonFile(PREFIX_PATH + "delete_video_response_ok.json");
final var model = parseToJavaObject(jsonFile, Video.class);
final var videoDto = this.videoMapper.mapToVideoDto(model);
when(this.videoRepository.findById(anyString())).thenReturn(Optional.of(model));
Expand All @@ -110,7 +112,7 @@ void delete_response_ok_test() {
@Test
void getById_response_ok_test() {
//Given
final var jsonFile = getJsonFile("getById_video_response_ok.json");
final var jsonFile = getJsonFile(PREFIX_PATH + "getById_video_response_ok.json");
final var model = parseToJavaObject(jsonFile, Video.class);
when(videoRepository.findById(anyString())).thenReturn(Optional.of(model));

Expand All @@ -124,7 +126,7 @@ void getById_response_ok_test() {
@Test
void getVideosByTitle_response_ok() {
//Given
final var jsonFile = getJsonFile("getById_video_response_ok.json");
final var jsonFile = getJsonFile(PREFIX_PATH + "getById_video_response_ok.json");
final var video = parseToJavaObject(jsonFile, Video.class);
final var videoDtoExpected = this.videoMapper.mapToVideoDto(video);
when(this.videoRepository.findByTitleLike(anyString())).thenReturn(List.of(video));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,15 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;
import org.springframework.data.domain.PageImpl;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

public class ParseJson {

private static final String JSON_FOLDER = "src/test/resources/json/video/";
private static final String JSON_FOLDER = "src/test/resources/json/";

/**
* Convert a JSON file in to a java object
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rating": "FREE",
"title": "Comedy",
"colorHex": "##2cfc03"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"id": "63f67ec16295ed744dd460cd",
"rating": "FREE",
"title": "Fantasy",
"colorHex": "#ffff83"
}
20 changes: 20 additions & 0 deletions src/test/resources/json/category/getAllCategories_response_ok.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[
{
"id": "63f67ec16295ed744dd460cd",
"rating": "FREE",
"title": "Fantasy",
"colorHex": "#ffff83"
},
{
"id": "63f7e674559a1b38c6b77b8a",
"rating": "TERROR",
"title": "terror",
"colorHex": "#000000"
},
{
"id": "string",
"rating": "Free",
"title": "comedy",
"colorHex": "blue"
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"id": "63680c011892283477b3e9b9",
"title": "Lord of the rings - The fellowship of the ring",
"description": "best movie ever",
"url": "https://lordoftherings.com",
"category": {
"id": "63f67ec16295ed744dd460cd",
"rating": "FREE",
"title": "Fantasy",
"colorHex": "#ffff83"
}
}
]

0 comments on commit dcd7c7d

Please sign in to comment.