Skip to content

Commit

Permalink
Update unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
daverbk committed Apr 1, 2024
1 parent bc858dc commit 1d5b5f2
Show file tree
Hide file tree
Showing 11 changed files with 331 additions and 107 deletions.
1 change: 1 addition & 0 deletions src/main/java/com/ypm/controller/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

@GetMapping("/success")
public ModelAndView success() {
return getModelAndView("success", "Login Success",
Expand Down
7 changes: 4 additions & 3 deletions src/main/java/com/ypm/controller/PlayListController.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
@RequestMapping("/playlists")
@RequiredArgsConstructor
public class PlayListController {

private final PlayListService playListService;
private final VideoService videosService;

Expand All @@ -44,8 +45,8 @@ public ResponseEntity<List<PlaylistItem>> getPlayListVideos(
return ResponseEntity.ok(videosService.getPlayListVideos(accessToken, playlistId));
}

@PutMapping("/{playlistId}/updateTitle")
public ResponseEntity<Playlist> updatePlayListName(
@PutMapping("/{playlistId}")
public ResponseEntity<Playlist> updatePlayListTitle(
@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authentication,
@PathVariable String playlistId,
@RequestBody PlaylistSnippet dataWithUpdatedTitle) throws IOException {
Expand All @@ -55,7 +56,7 @@ public ResponseEntity<Playlist> updatePlayListName(
.getTokenValue();

String newTitle = dataWithUpdatedTitle.getTitle();
return ResponseEntity.ok(playListService.updatePlayListName(accessToken, playlistId, newTitle));
return ResponseEntity.ok(playListService.updatePlayListTitle(accessToken, playlistId, newTitle));
}

@PutMapping("/{playlistId}/{targetPlaylistId}")
Expand Down
1 change: 1 addition & 0 deletions src/main/java/com/ypm/controller/VideoController.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
@RequestMapping("/videos")
@RequiredArgsConstructor
public class VideoController {

private final VideoService videosService;

@DeleteMapping("/{videoId}")
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/ypm/service/PlayListService.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public List<Playlist> getPlayLists(String accessToken) throws IOException {
.getItems();
}

public Playlist updatePlayListName(String accessToken, String playListId, String newTitle)
throws IOException {
public Playlist updatePlayListTitle(String accessToken, String playListId,
String newTitle) throws IOException {

Playlist playlistToEdit = getPlayListById(accessToken, playListId);
playlistToEdit.getSnippet().setTitle(newTitle);
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/ypm/service/VideoService.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ public void deleteVideo(String accessToken, String id) throws IOException {
.execute();
}

public List<PlaylistItem> getPlayListVideos(String accessToken, String playListId)
throws IOException {
public List<PlaylistItem> getPlayListVideos(String accessToken,
String playListId) throws IOException {

return youTubeClient
.playlistItems()
Expand Down
8 changes: 4 additions & 4 deletions src/test/java/com/ypm/controller/AuthControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@

@SpringBootTest
@AutoConfigureMockMvc
public class AuthControllerTest {
class AuthControllerTest {

@Autowired
private MockMvc mockMvc;

Expand All @@ -24,7 +25,7 @@ void givenOAuth2Login_whenAuthSuccess_thenLoginSuccessful() throws Exception {
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.view().name("auth"))
.andExpect(MockMvcResultMatchers.model().attribute("type", "success"))
.andExpect(MockMvcResultMatchers.model().attribute("title", "Login Successful"))
.andExpect(MockMvcResultMatchers.model().attribute("title", "Login Success"))
.andExpect(MockMvcResultMatchers.model().attribute("message",
"Welcome back! You have successfully logged in."));
}
Expand All @@ -38,7 +39,6 @@ void givenMockUser_whenAuthError_thenLoginError() throws Exception {
.andExpect(MockMvcResultMatchers.model().attribute("type", "error"))
.andExpect(MockMvcResultMatchers.model().attribute("title", "Login Error"))
.andExpect(MockMvcResultMatchers.model().attribute("message",
"Sorry, there was an error with your login credentials. Please try again."));
"An error occurred while logging in. Please try again."));
}

}
87 changes: 69 additions & 18 deletions src/test/java/com/ypm/controller/PlayListControllerTest.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.ypm.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.services.youtube.model.Playlist;
import com.google.api.services.youtube.model.PlaylistItem;
import com.google.api.services.youtube.model.PlaylistItemSnippet;
import com.google.api.services.youtube.model.PlaylistSnippet;
import com.ypm.service.PlayListService;
import com.ypm.service.VideoService;
Expand All @@ -10,6 +12,7 @@
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.test.web.servlet.MockMvc;

Expand All @@ -20,56 +23,104 @@
import static org.mockito.Mockito.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oauth2Login;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest
@AutoConfigureMockMvc
class PlayListControllerTest {

@MockBean
private PlayListService playListService;

@MockBean
private VideoService videosService;

@Autowired
private ClientRegistrationRepository clientRegistrationRepository;

@Autowired
private MockMvc mockMvc;

@MockBean
private PlayListService playListService;

@MockBean
private VideoService videosService;
@Autowired
private ObjectMapper objectMapper;

@Test
void givenCorrectRequest_whenGetPlayLists_thenResponseContainsPlayListName() throws Exception {
var login = oauth2Login()
.clientRegistration(this.clientRegistrationRepository.findByRegistrationId("google"));

Playlist playlist = new Playlist();
playlist.setSnippet(new PlaylistSnippet().setTitle("Test Playlist"));
List<Playlist> playlists = Collections.singletonList(playlist);

when(playListService.getPlayLists(any())).thenReturn(playlists);

mockMvc.perform(get("/playlists")
.with(oauth2Login()
.clientRegistration(this.clientRegistrationRepository.findByRegistrationId("google"))))
mockMvc.perform(get("/playlists").with(login))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$[0].snippet.title").value("Test Playlist"));
.andExpect(content().json(objectMapper.writeValueAsString(playlists)));

verify(playListService, times(1)).getPlayLists(any());
}

@Test
void givenCorrectRequest_whenGetPlayListVideos_thenResponseContainsVideoTitle() throws Exception {
var login = oauth2Login()
.clientRegistration(this.clientRegistrationRepository.findByRegistrationId("google"));

PlaylistItem video = new PlaylistItem();
video.getSnippet().setTitle("Video Title");
video.setSnippet(new PlaylistItemSnippet().setTitle("New Title"));
List<PlaylistItem> videos = List.of(video);

when(videosService.getPlayListVideos(any(), any())).thenReturn(videos);

mockMvc.perform(get("/playlists/{playlistId}", "playlistId")
.with(oauth2Login()
.clientRegistration(this.clientRegistrationRepository.findByRegistrationId("google"))))
mockMvc.perform(get("/playlists/{playlistId}", "someId").with(login))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$[0].title").value("Test Video"));
.andExpect(content().json(objectMapper.writeValueAsString(videos)));

verify(videosService, times(1)).getPlayListVideos(any(), any());
}

@Test
void givenCorrectRequest_whenUpdatePlayListTitle_thenResponseContainsUpdatedTitle() throws Exception {
var login = oauth2Login()
.clientRegistration(this.clientRegistrationRepository.findByRegistrationId("google"));

Playlist playlist = new Playlist();
playlist.setSnippet(new PlaylistSnippet().setTitle("New Title"));

when(playListService.updatePlayListTitle(any(), any(), any())).thenReturn(playlist);

mockMvc.perform(put("/playlists/{playlistId}", "someId")
.with(login)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(playlist)))
.andExpect(status().isOk())
.andExpect(content().json(objectMapper.writeValueAsString(playlist)));

verify(playListService, times(1))
.updatePlayListTitle(any(), any(), any());
}

@Test
void givenCorrectRequest_whenMoveVideos_thenResponseContainsMovedVideos() throws Exception {
var login = oauth2Login()
.clientRegistration(this.clientRegistrationRepository.findByRegistrationId("google"));

List<String> videosIds = List.of("videoId1", "videoId2");
List<PlaylistItem> videos = List.of(new PlaylistItem(), new PlaylistItem());

when(videosService.moveVideos(any(), any(), any(), any())).thenReturn(videos);

mockMvc.perform(put("/playlists/{playlistId}/{targetPlaylistId}",
"someId", "targetId")
.with(login)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(videosIds)))
.andExpect(status().isOk())
.andExpect(content().json(objectMapper.writeValueAsString(videos)));

verify(videosService, times(1))
.moveVideos(any(), any(), any(), any());
}
}
5 changes: 3 additions & 2 deletions src/test/java/com/ypm/controller/VideoControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@

@SpringBootTest
@AutoConfigureMockMvc
public class VideoControllerTest {
class VideoControllerTest {

@MockBean
private VideoService videosService;

Expand All @@ -34,7 +35,7 @@ void givenCorrectRequest_whenDeleteVideos_thenNoContent() throws Exception {

doNothing().when(videosService).deleteVideo(any(), any());

mockMvc.perform(delete("/videos/{videoId}", "videoId").with(login))
mockMvc.perform(delete("/videos/{videoId}", "someId").with(login))
.andExpect(status().isNoContent());
}
}
100 changes: 100 additions & 0 deletions src/test/java/com/ypm/service/PlayListServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package com.ypm.service;

import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Playlist;
import com.google.api.services.youtube.model.PlaylistListResponse;
import com.google.api.services.youtube.model.PlaylistSnippet;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;

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

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@SpringBootTest
public class PlayListServiceTest {

private final String accessToken =
"ey.aphktnp.eyJzdWIiOiJ0ZXN0IiwibmFtZSI6IlRlc3QiLCJpYXQiOjE2MjMwNjMwMjJ9";

@Mock
private YouTube youTubeClient;

@InjectMocks
private PlayListService playListService;

@Test
void givenCorrectData_whenGetPlayLists_thenPlaylistsFound() throws IOException {
var playlists = mock(YouTube.Playlists.class);
var playlistsList = mock(YouTube.Playlists.List.class);
var expectedPlaylist = new Playlist();
expectedPlaylist.setSnippet(new PlaylistSnippet().setTitle("Playlist Title"));
var playlistsListResponse = new PlaylistListResponse()
.setItems(List.of(expectedPlaylist));

when(youTubeClient.playlists()).thenReturn(playlists);
when(playlists.list(List.of("snippet"))).thenReturn(playlistsList);
when(playlistsList.setAccessToken(accessToken)).thenReturn(playlistsList);
when(playlistsList.setMine(true)).thenReturn(playlistsList);
when(playlistsList.execute()).thenReturn(playlistsListResponse);

List<Playlist> result = playListService.getPlayLists(accessToken);

assertEquals(1, result.size());
assertEquals(expectedPlaylist, result.get(0));
assertEquals("Playlist Title", result.get(0).getSnippet().getTitle());
}

@Test
void givenCorrectData_whenUpdatePlayListTitle_thenPlayListTitleUpdated() throws IOException {
var playlists = mock(YouTube.Playlists.class);
var playlistsList = mock(YouTube.Playlists.List.class);
var playlistUpdate = mock(YouTube.Playlists.Update.class);
var expectedPlaylist = new Playlist();
expectedPlaylist.setSnippet(new PlaylistSnippet().setTitle("Playlist Title"));
var playlistsListResponse = new PlaylistListResponse()
.setItems(List.of(expectedPlaylist));

when(youTubeClient.playlists()).thenReturn(playlists);
when(playlists.list(List.of("snippet"))).thenReturn(playlistsList);
when(playlistsList.setAccessToken(accessToken)).thenReturn(playlistsList);
when(playlistsList.setMine(true)).thenReturn(playlistsList);
when(playlistsList.setId(any())).thenReturn(playlistsList);
when(playlistsList.execute()).thenReturn(playlistsListResponse);
when(playlists.update(List.of("snippet"), expectedPlaylist)).thenReturn(playlistUpdate);
when(playlistUpdate.setAccessToken(accessToken)).thenReturn(playlistUpdate);
when(playlistUpdate.execute()).thenReturn(expectedPlaylist);

Playlist result = playListService.updatePlayListTitle(accessToken, "playlistId", "New Title");

assertEquals("New Title", result.getSnippet().getTitle());
}

@Test
void givenCorrectData_whenGetPlayListById_thenPlayListFound() throws IOException {
var playlists = mock(YouTube.Playlists.class);
var playlistsList = mock(YouTube.Playlists.List.class);
var expectedPlaylist = new Playlist();
expectedPlaylist.setSnippet(new PlaylistSnippet().setTitle("Playlist Title"));
var playlistsListResponse = new PlaylistListResponse()
.setItems(List.of(expectedPlaylist));

when(youTubeClient.playlists()).thenReturn(playlists);
when(playlists.list(List.of("snippet"))).thenReturn(playlistsList);
when(playlistsList.setAccessToken(accessToken)).thenReturn(playlistsList);
when(playlistsList.setMine(true)).thenReturn(playlistsList);
when(playlistsList.setId(List.of("playlistId"))).thenReturn(playlistsList);
when(playlistsList.execute()).thenReturn(playlistsListResponse);

Playlist result = playListService.getPlayListById(accessToken, "playlistId");

assertEquals(expectedPlaylist, result);
assertEquals("Playlist Title", result.getSnippet().getTitle());
}
}
Loading

0 comments on commit 1d5b5f2

Please sign in to comment.