fix: 后端代码格式化

This commit is contained in:
Tim
2025-09-18 14:42:25 +08:00
parent 70f7442f0c
commit 72b2b82e02
325 changed files with 15341 additions and 12370 deletions

View File

@@ -1,83 +1,90 @@
package com.openisle.controller;
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.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.boot.test.mock.mockito.MockBean;
import com.openisle.config.CustomAccessDeniedHandler;
import com.openisle.config.SecurityConfig;
import com.openisle.service.JwtService;
import com.openisle.repository.UserRepository;
import com.openisle.service.UserVisitService;
import com.openisle.model.Role;
import com.openisle.model.User;
import java.util.Optional;
import org.mockito.Mockito;
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 com.openisle.config.CustomAccessDeniedHandler;
import com.openisle.config.SecurityConfig;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.JwtService;
import com.openisle.service.UserVisitService;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
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.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(AdminController.class)
@AutoConfigureMockMvc
@Import({SecurityConfig.class, CustomAccessDeniedHandler.class})
@Import({ SecurityConfig.class, CustomAccessDeniedHandler.class })
class AdminControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private JwtService jwtService;
@MockBean
private UserRepository userRepository;
@MockBean
private UserVisitService userVisitService;
@Autowired
private MockMvc mockMvc;
@Test
void adminHelloReturnsMessage() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("adminToken")).thenReturn("admin");
User admin = new User();
admin.setUsername("admin");
admin.setPassword("p");
admin.setEmail("a@b.com");
admin.setRole(Role.ADMIN);
Mockito.when(userRepository.findByUsername("admin")).thenReturn(Optional.of(admin));
@MockBean
private JwtService jwtService;
mockMvc.perform(get("/api/admin/hello").header("Authorization", "Bearer adminToken"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("Hello, Admin User"));
}
@MockBean
private UserRepository userRepository;
@Test
void adminHelloMissingToken() throws Exception {
mockMvc.perform(get("/api/admin/hello"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Missing token"));
}
@MockBean
private UserVisitService userVisitService;
@Test
void adminHelloInvalidToken() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("bad")).thenThrow(new RuntimeException());
@Test
void adminHelloReturnsMessage() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("adminToken")).thenReturn("admin");
User admin = new User();
admin.setUsername("admin");
admin.setPassword("p");
admin.setEmail("a@b.com");
admin.setRole(Role.ADMIN);
Mockito.when(userRepository.findByUsername("admin")).thenReturn(Optional.of(admin));
mockMvc.perform(get("/api/admin/hello").header("Authorization", "Bearer bad"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Invalid or expired token"));
}
mockMvc
.perform(get("/api/admin/hello").header("Authorization", "Bearer adminToken"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("Hello, Admin User"));
}
@Test
void adminHelloNotAdmin() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("userToken")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
@Test
void adminHelloMissingToken() throws Exception {
mockMvc
.perform(get("/api/admin/hello"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Missing token"));
}
mockMvc.perform(get("/api/admin/hello").header("Authorization", "Bearer userToken"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Unauthorized"));
}
@Test
void adminHelloInvalidToken() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("bad")).thenThrow(new RuntimeException());
mockMvc
.perform(get("/api/admin/hello").header("Authorization", "Bearer bad"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Invalid or expired token"));
}
@Test
void adminHelloNotAdmin() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("userToken")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
mockMvc
.perform(get("/api/admin/hello").header("Authorization", "Bearer userToken"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Unauthorized"));
}
}

View File

@@ -1,11 +1,18 @@
package com.openisle.controller;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.openisle.model.Notification;
import com.openisle.model.NotificationType;
import com.openisle.model.User;
import com.openisle.repository.NotificationRepository;
import com.openisle.repository.UserRepository;
import com.openisle.service.EmailSender;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
@@ -13,64 +20,59 @@ 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.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(AdminUserController.class)
@AutoConfigureMockMvc(addFilters = false)
class AdminUserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserRepository userRepository;
@MockBean
private NotificationRepository notificationRepository;
@MockBean
private EmailSender emailSender;
@Autowired
private MockMvc mockMvc;
@Test
void approveMarksNotificationsRead() throws Exception {
User u = new User();
u.setId(1L);
u.setEmail("a@a.com");
when(userRepository.findById(1L)).thenReturn(Optional.of(u));
@MockBean
private UserRepository userRepository;
Notification n = new Notification();
n.setId(2L);
n.setRead(false);
when(notificationRepository.findByTypeAndFromUser(NotificationType.REGISTER_REQUEST, u))
.thenReturn(List.of(n));
@MockBean
private NotificationRepository notificationRepository;
mockMvc.perform(post("/api/admin/users/1/approve"))
.andExpect(status().isOk());
@MockBean
private EmailSender emailSender;
assertTrue(n.isRead());
verify(notificationRepository).saveAll(List.of(n));
}
@Test
void approveMarksNotificationsRead() throws Exception {
User u = new User();
u.setId(1L);
u.setEmail("a@a.com");
when(userRepository.findById(1L)).thenReturn(Optional.of(u));
@Test
void rejectMarksNotificationsRead() throws Exception {
User u = new User();
u.setId(1L);
u.setEmail("a@a.com");
when(userRepository.findById(1L)).thenReturn(Optional.of(u));
Notification n = new Notification();
n.setId(2L);
n.setRead(false);
when(
notificationRepository.findByTypeAndFromUser(NotificationType.REGISTER_REQUEST, u)
).thenReturn(List.of(n));
Notification n = new Notification();
n.setId(2L);
n.setRead(false);
when(notificationRepository.findByTypeAndFromUser(NotificationType.REGISTER_REQUEST, u))
.thenReturn(List.of(n));
mockMvc.perform(post("/api/admin/users/1/approve")).andExpect(status().isOk());
mockMvc.perform(post("/api/admin/users/1/reject"))
.andExpect(status().isOk());
assertTrue(n.isRead());
verify(notificationRepository).saveAll(List.of(n));
}
assertTrue(n.isRead());
verify(notificationRepository).saveAll(List.of(n));
}
@Test
void rejectMarksNotificationsRead() throws Exception {
User u = new User();
u.setId(1L);
u.setEmail("a@a.com");
when(userRepository.findById(1L)).thenReturn(Optional.of(u));
Notification n = new Notification();
n.setId(2L);
n.setRead(false);
when(
notificationRepository.findByTypeAndFromUser(NotificationType.REGISTER_REQUEST, u)
).thenReturn(List.of(n));
mockMvc.perform(post("/api/admin/users/1/reject")).andExpect(status().isOk());
assertTrue(n.isRead());
verify(notificationRepository).saveAll(List.of(n));
}
}

View File

@@ -1,10 +1,18 @@
package com.openisle.controller;
import com.openisle.model.User;
import com.openisle.service.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.openisle.model.RegisterMode;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.*;
import com.openisle.util.VerifyType;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -14,100 +22,118 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Map;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(AuthController.class)
@AutoConfigureMockMvc(addFilters = false)
class AuthControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@MockBean
private JwtService jwtService;
@MockBean
private EmailSender emailService;
@MockBean
private CaptchaService captchaService;
@MockBean
private GoogleAuthService googleAuthService;
@MockBean
private RegisterModeService registerModeService;
@MockBean
private GithubAuthService githubAuthService;
@MockBean
private DiscordAuthService discordAuthService;
@MockBean
private TwitterAuthService twitterAuthService;
@MockBean
private NotificationService notificationService;
@MockBean
private UserRepository userRepository;
@Autowired
private MockMvc mockMvc;
@Test
void registerSendsEmail() throws Exception {
User user = new User();
user.setEmail("a@b.com");
user.setUsername("u");
user.setVerificationCode("123456");
Mockito.when(registerModeService.getRegisterMode()).thenReturn(RegisterMode.DIRECT);
Mockito.when(userService.register(eq("u"), eq("a@b.com"), eq("p"), any(), eq(RegisterMode.DIRECT))).thenReturn(user);
@MockBean
private UserService userService;
mockMvc.perform(post("/api/auth/register")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"u\",\"email\":\"a@b.com\",\"password\":\"p\",\"reason\":\"test reason more than twenty\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").exists());
@MockBean
private JwtService jwtService;
Mockito.verify(emailService).sendEmail(eq("a@b.com"), any(), any());
}
@MockBean
private EmailSender emailService;
@Test
void verifyCodeEndpoint() throws Exception {
User user = new User();
user.setUsername("u");
Mockito.when(userService.verifyCode(user, "123", VerifyType.REGISTER)).thenReturn(true);
Mockito.when(jwtService.generateReasonToken("u")).thenReturn("reason_token");
@MockBean
private CaptchaService captchaService;
mockMvc.perform(post("/api/auth/verify")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"u\",\"code\":\"123\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("Verified"));
}
@MockBean
private GoogleAuthService googleAuthService;
@Test
void loginReturnsToken() throws Exception {
User user = new User();
user.setUsername("u");
user.setVerified(true);
Mockito.when(userService.findByUsername("u")).thenReturn(Optional.of(user));
Mockito.when(userService.matchesPassword(user, "p")).thenReturn(true);
Mockito.when(jwtService.generateToken("u")).thenReturn("token");
@MockBean
private RegisterModeService registerModeService;
mockMvc.perform(post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"u\",\"password\":\"p\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.token").value("token"));
}
@MockBean
private GithubAuthService githubAuthService;
@Test
void loginFails() throws Exception {
Mockito.when(userService.findByUsername("u")).thenReturn(Optional.empty());
@MockBean
private DiscordAuthService discordAuthService;
mockMvc.perform(post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"u\",\"password\":\"bad\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.reason_code").value("INVALID_CREDENTIALS"));
}
@MockBean
private TwitterAuthService twitterAuthService;
@MockBean
private NotificationService notificationService;
@MockBean
private UserRepository userRepository;
@Test
void registerSendsEmail() throws Exception {
User user = new User();
user.setEmail("a@b.com");
user.setUsername("u");
user.setVerificationCode("123456");
Mockito.when(registerModeService.getRegisterMode()).thenReturn(RegisterMode.DIRECT);
Mockito.when(
userService.register(eq("u"), eq("a@b.com"), eq("p"), any(), eq(RegisterMode.DIRECT))
).thenReturn(user);
mockMvc
.perform(
post("/api/auth/register")
.contentType(MediaType.APPLICATION_JSON)
.content(
"{\"username\":\"u\",\"email\":\"a@b.com\",\"password\":\"p\",\"reason\":\"test reason more than twenty\"}"
)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").exists());
Mockito.verify(emailService).sendEmail(eq("a@b.com"), any(), any());
}
@Test
void verifyCodeEndpoint() throws Exception {
User user = new User();
user.setUsername("u");
Mockito.when(userService.verifyCode(user, "123", VerifyType.REGISTER)).thenReturn(true);
Mockito.when(jwtService.generateReasonToken("u")).thenReturn("reason_token");
mockMvc
.perform(
post("/api/auth/verify")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"u\",\"code\":\"123\"}")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("Verified"));
}
@Test
void loginReturnsToken() throws Exception {
User user = new User();
user.setUsername("u");
user.setVerified(true);
Mockito.when(userService.findByUsername("u")).thenReturn(Optional.of(user));
Mockito.when(userService.matchesPassword(user, "p")).thenReturn(true);
Mockito.when(jwtService.generateToken("u")).thenReturn("token");
mockMvc
.perform(
post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"u\",\"password\":\"p\"}")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.token").value("token"));
}
@Test
void loginFails() throws Exception {
Mockito.when(userService.findByUsername("u")).thenReturn(Optional.empty());
mockMvc
.perform(
post("/api/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"u\",\"password\":\"bad\"}")
)
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.reason_code").value("INVALID_CREDENTIALS"));
}
}

View File

@@ -1,10 +1,15 @@
package com.openisle.controller;
import static org.mockito.ArgumentMatchers.eq;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.openisle.mapper.CategoryMapper;
import com.openisle.mapper.PostMapper;
import com.openisle.model.Category;
import com.openisle.service.CategoryService;
import com.openisle.service.PostService;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -15,89 +20,98 @@ import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.mockito.ArgumentMatchers.eq;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(CategoryController.class)
@AutoConfigureMockMvc(addFilters = false)
@Import(CategoryMapper.class)
class CategoryControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private CategoryService categoryService;
@Autowired
private MockMvc mockMvc;
@MockBean
private PostService postService;
@MockBean
private CategoryService categoryService;
@MockBean
private PostMapper postMapper;
@MockBean
private PostService postService;
@Test
void createAndGetCategory() throws Exception {
Category c = new Category();
c.setId(1L);
c.setName("tech");
c.setDescription("d");
c.setIcon("i");
c.setSmallIcon("s1");
Mockito.when(categoryService.createCategory(eq("tech"), eq("d"), eq("i"), eq("s1"))).thenReturn(c);
Mockito.when(categoryService.getCategory(1L)).thenReturn(c);
@MockBean
private PostMapper postMapper;
mockMvc.perform(post("/api/categories")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"tech\",\"description\":\"d\",\"icon\":\"i\",\"smallIcon\":\"s1\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("tech"))
.andExpect(jsonPath("$.description").value("d"))
.andExpect(jsonPath("$.icon").value("i"))
.andExpect(jsonPath("$.smallIcon").value("s1"));
@Test
void createAndGetCategory() throws Exception {
Category c = new Category();
c.setId(1L);
c.setName("tech");
c.setDescription("d");
c.setIcon("i");
c.setSmallIcon("s1");
Mockito.when(categoryService.createCategory(eq("tech"), eq("d"), eq("i"), eq("s1"))).thenReturn(
c
);
Mockito.when(categoryService.getCategory(1L)).thenReturn(c);
mockMvc.perform(get("/api/categories/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1));
}
mockMvc
.perform(
post("/api/categories")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"tech\",\"description\":\"d\",\"icon\":\"i\",\"smallIcon\":\"s1\"}")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("tech"))
.andExpect(jsonPath("$.description").value("d"))
.andExpect(jsonPath("$.icon").value("i"))
.andExpect(jsonPath("$.smallIcon").value("s1"));
@Test
void listCategories() throws Exception {
Category c = new Category();
c.setId(2L);
c.setName("life");
c.setDescription("d2");
c.setIcon("i2");
c.setSmallIcon("s2");
Mockito.when(categoryService.listCategories()).thenReturn(List.of(c));
mockMvc
.perform(get("/api/categories/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1));
}
mockMvc.perform(get("/api/categories"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].name").value("life"))
.andExpect(jsonPath("$[0].description").value("d2"))
.andExpect(jsonPath("$[0].icon").value("i2"))
.andExpect(jsonPath("$[0].smallIcon").value("s2"));
}
@Test
void listCategories() throws Exception {
Category c = new Category();
c.setId(2L);
c.setName("life");
c.setDescription("d2");
c.setIcon("i2");
c.setSmallIcon("s2");
Mockito.when(categoryService.listCategories()).thenReturn(List.of(c));
@Test
void updateCategory() throws Exception {
Category c = new Category();
c.setId(3L);
c.setName("tech");
c.setDescription("d3");
c.setIcon("i3");
c.setSmallIcon("s3");
Mockito.when(categoryService.updateCategory(eq(3L), eq("tech"), eq("d3"), eq("i3"), eq("s3"))).thenReturn(c);
mockMvc
.perform(get("/api/categories"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].name").value("life"))
.andExpect(jsonPath("$[0].description").value("d2"))
.andExpect(jsonPath("$[0].icon").value("i2"))
.andExpect(jsonPath("$[0].smallIcon").value("s2"));
}
mockMvc.perform(put("/api/categories/3")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"tech\",\"description\":\"d3\",\"icon\":\"i3\",\"smallIcon\":\"s3\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(3))
.andExpect(jsonPath("$.name").value("tech"))
.andExpect(jsonPath("$.description").value("d3"))
.andExpect(jsonPath("$.icon").value("i3"))
.andExpect(jsonPath("$.smallIcon").value("s3"));
}
@Test
void updateCategory() throws Exception {
Category c = new Category();
c.setId(3L);
c.setName("tech");
c.setDescription("d3");
c.setIcon("i3");
c.setSmallIcon("s3");
Mockito.when(
categoryService.updateCategory(eq(3L), eq("tech"), eq("d3"), eq("i3"), eq("s3"))
).thenReturn(c);
mockMvc
.perform(
put("/api/categories/3")
.contentType(MediaType.APPLICATION_JSON)
.content(
"{\"name\":\"tech\",\"description\":\"d3\",\"icon\":\"i3\",\"smallIcon\":\"s3\"}"
)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(3))
.andExpect(jsonPath("$.name").value("tech"))
.andExpect(jsonPath("$.description").value("d3"))
.andExpect(jsonPath("$.icon").value("i3"))
.andExpect(jsonPath("$.smallIcon").value("s3"));
}
}

View File

@@ -1,5 +1,12 @@
package com.openisle.controller;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.openisle.dto.CommentDto;
import com.openisle.mapper.CommentMapper;
import com.openisle.model.Comment;
@@ -9,6 +16,8 @@ import com.openisle.service.CaptchaService;
import com.openisle.service.CommentService;
import com.openisle.service.LevelService;
import com.openisle.service.ReactionService;
import java.time.LocalDateTime;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -18,84 +27,86 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDateTime;
import java.util.List;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.any;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(CommentController.class)
@AutoConfigureMockMvc(addFilters = false)
class CommentControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private CommentService commentService;
@MockBean
private CaptchaService captchaService;
@MockBean
private LevelService levelService;
@MockBean
private ReactionService reactionService;
@MockBean
private CommentMapper commentMapper;
@Autowired
private MockMvc mockMvc;
private Comment createComment(Long id, String content, String authorName) {
User user = new User();
user.setUsername(authorName);
Comment c = new Comment();
c.setId(id);
c.setContent(content);
c.setCreatedAt(LocalDateTime.now());
c.setAuthor(user);
c.setPost(new Post());
return c;
}
@MockBean
private CommentService commentService;
@Test
void createAndListComments() throws Exception {
Comment comment = createComment(1L, "hi", "bob");
Mockito.when(commentService.addComment(eq("bob"), eq(1L), eq("hi"))).thenReturn(comment);
Mockito.when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of(comment));
Mockito.when(commentService.getReplies(1L)).thenReturn(List.of());
Mockito.when(reactionService.getReactionsForComment(1L)).thenReturn(List.of());
CommentDto dto = new CommentDto();
dto.setId(comment.getId());
dto.setContent(comment.getContent());
Mockito.when(commentMapper.toDto(comment)).thenReturn(dto);
Mockito.when(commentMapper.toDtoWithReplies(comment)).thenReturn(dto);
@MockBean
private CaptchaService captchaService;
mockMvc.perform(post("/api/posts/1/comments")
.contentType("application/json")
.content("{\"content\":\"hi\"}")
.principal(new UsernamePasswordAuthenticationToken("bob", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content").value("hi"));
@MockBean
private LevelService levelService;
mockMvc.perform(get("/api/posts/1/comments"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(1));
}
@MockBean
private ReactionService reactionService;
@Test
void replyComment() throws Exception {
Comment reply = createComment(2L, "re", "alice");
Mockito.when(commentService.addReply(eq("alice"), eq(1L), eq("re"))).thenReturn(reply);
CommentDto dto = new CommentDto();
dto.setId(reply.getId());
dto.setContent(reply.getContent());
Mockito.when(commentMapper.toDto(reply)).thenReturn(dto);
@MockBean
private CommentMapper commentMapper;
mockMvc.perform(post("/api/comments/1/replies")
.contentType("application/json")
.content("{\"content\":\"re\"}")
.principal(new UsernamePasswordAuthenticationToken("alice", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(2));
}
private Comment createComment(Long id, String content, String authorName) {
User user = new User();
user.setUsername(authorName);
Comment c = new Comment();
c.setId(id);
c.setContent(content);
c.setCreatedAt(LocalDateTime.now());
c.setAuthor(user);
c.setPost(new Post());
return c;
}
@Test
void createAndListComments() throws Exception {
Comment comment = createComment(1L, "hi", "bob");
Mockito.when(commentService.addComment(eq("bob"), eq(1L), eq("hi"))).thenReturn(comment);
Mockito.when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of(comment));
Mockito.when(commentService.getReplies(1L)).thenReturn(List.of());
Mockito.when(reactionService.getReactionsForComment(1L)).thenReturn(List.of());
CommentDto dto = new CommentDto();
dto.setId(comment.getId());
dto.setContent(comment.getContent());
Mockito.when(commentMapper.toDto(comment)).thenReturn(dto);
Mockito.when(commentMapper.toDtoWithReplies(comment)).thenReturn(dto);
mockMvc
.perform(
post("/api/posts/1/comments")
.contentType("application/json")
.content("{\"content\":\"hi\"}")
.principal(new UsernamePasswordAuthenticationToken("bob", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.content").value("hi"));
mockMvc
.perform(get("/api/posts/1/comments"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(1));
}
@Test
void replyComment() throws Exception {
Comment reply = createComment(2L, "re", "alice");
Mockito.when(commentService.addReply(eq("alice"), eq(1L), eq("re"))).thenReturn(reply);
CommentDto dto = new CommentDto();
dto.setId(reply.getId());
dto.setContent(reply.getContent());
Mockito.when(commentMapper.toDto(reply)).thenReturn(dto);
mockMvc
.perform(
post("/api/comments/1/replies")
.contentType("application/json")
.content("{\"content\":\"re\"}")
.principal(new UsernamePasswordAuthenticationToken("alice", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(2));
}
}

View File

@@ -1,68 +1,74 @@
package com.openisle.controller;
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.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.boot.test.mock.mockito.MockBean;
import com.openisle.config.CustomAccessDeniedHandler;
import com.openisle.config.SecurityConfig;
import com.openisle.service.JwtService;
import com.openisle.repository.UserRepository;
import com.openisle.service.UserVisitService;
import com.openisle.model.Role;
import com.openisle.model.User;
import java.util.Optional;
import org.mockito.Mockito;
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 com.openisle.config.CustomAccessDeniedHandler;
import com.openisle.config.SecurityConfig;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.JwtService;
import com.openisle.service.UserVisitService;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
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.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(HelloController.class)
@AutoConfigureMockMvc
@Import({SecurityConfig.class, CustomAccessDeniedHandler.class})
@Import({ SecurityConfig.class, CustomAccessDeniedHandler.class })
class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private JwtService jwtService;
@MockBean
private UserRepository userRepository;
@MockBean
private UserVisitService userVisitService;
@Autowired
private MockMvc mockMvc;
@Test
void helloReturnsMessage() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
@MockBean
private JwtService jwtService;
mockMvc.perform(get("/api/hello").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("Hello, Authenticated User"));
}
@MockBean
private UserRepository userRepository;
@Test
void helloMissingToken() throws Exception {
mockMvc.perform(get("/api/hello"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Missing token"));
}
@MockBean
private UserVisitService userVisitService;
@Test
void helloInvalidToken() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("bad")).thenThrow(new RuntimeException());
@Test
void helloReturnsMessage() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
mockMvc.perform(get("/api/hello").header("Authorization", "Bearer bad"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Invalid or expired token"));
}
mockMvc
.perform(get("/api/hello").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message").value("Hello, Authenticated User"));
}
@Test
void helloMissingToken() throws Exception {
mockMvc
.perform(get("/api/hello"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Missing token"));
}
@Test
void helloInvalidToken() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("bad")).thenThrow(new RuntimeException());
mockMvc
.perform(get("/api/hello").header("Authorization", "Bearer bad"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.error").value("Invalid or expired token"));
}
}

View File

@@ -1,8 +1,14 @@
package com.openisle.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.openisle.dto.CommentMedalDto;
import com.openisle.model.MedalType;
import com.openisle.service.MedalService;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -12,63 +18,66 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(MedalController.class)
@AutoConfigureMockMvc(addFilters = false)
class MedalControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private MedalService medalService;
@Autowired
private MockMvc mockMvc;
@Test
void listMedals() throws Exception {
CommentMedalDto medal = new CommentMedalDto();
medal.setTitle("评论达人");
medal.setType(MedalType.COMMENT);
Mockito.when(medalService.getMedals(null)).thenReturn(List.of(medal));
@MockBean
private MedalService medalService;
mockMvc.perform(get("/api/medals"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("评论达人"));
}
@Test
void listMedals() throws Exception {
CommentMedalDto medal = new CommentMedalDto();
medal.setTitle("评论达人");
medal.setType(MedalType.COMMENT);
Mockito.when(medalService.getMedals(null)).thenReturn(List.of(medal));
@Test
void listMedalsWithUser() throws Exception {
CommentMedalDto medal = new CommentMedalDto();
medal.setCompleted(true);
medal.setType(MedalType.COMMENT);
Mockito.when(medalService.getMedals(1L)).thenReturn(List.of(medal));
mockMvc
.perform(get("/api/medals"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("评论达人"));
}
mockMvc.perform(get("/api/medals").param("userId", "1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].completed").value(true));
}
@Test
void listMedalsWithUser() throws Exception {
CommentMedalDto medal = new CommentMedalDto();
medal.setCompleted(true);
medal.setType(MedalType.COMMENT);
Mockito.when(medalService.getMedals(1L)).thenReturn(List.of(medal));
@Test
void selectMedal() throws Exception {
mockMvc.perform(post("/api/medals/select")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"type\":\"COMMENT\"}")
.principal(() -> "user"))
.andExpect(status().isOk());
}
mockMvc
.perform(get("/api/medals").param("userId", "1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].completed").value(true));
}
@Test
void selectMedalBadRequest() throws Exception {
Mockito.doThrow(new IllegalArgumentException()).when(medalService)
.selectMedal("user", MedalType.COMMENT);
mockMvc.perform(post("/api/medals/select")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"type\":\"COMMENT\"}")
.principal(() -> "user"))
.andExpect(status().isBadRequest());
}
@Test
void selectMedal() throws Exception {
mockMvc
.perform(
post("/api/medals/select")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"type\":\"COMMENT\"}")
.principal(() -> "user")
)
.andExpect(status().isOk());
}
@Test
void selectMedalBadRequest() throws Exception {
Mockito.doThrow(new IllegalArgumentException())
.when(medalService)
.selectMedal("user", MedalType.COMMENT);
mockMvc
.perform(
post("/api/medals/select")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"type\":\"COMMENT\"}")
.principal(() -> "user")
)
.andExpect(status().isBadRequest());
}
}

View File

@@ -1,5 +1,9 @@
package com.openisle.controller;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.openisle.dto.NotificationDto;
import com.openisle.dto.PostSummaryDto;
import com.openisle.mapper.NotificationMapper;
@@ -7,6 +11,8 @@ import com.openisle.model.Notification;
import com.openisle.model.NotificationType;
import com.openisle.model.Post;
import com.openisle.service.NotificationService;
import java.time.LocalDateTime;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
@@ -16,88 +22,92 @@ import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDateTime;
import java.util.List;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.mockito.Mockito.*;
@WebMvcTest(NotificationController.class)
@AutoConfigureMockMvc(addFilters = false)
class NotificationControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private MockMvc mockMvc;
@MockBean
private NotificationService notificationService;
@MockBean
private NotificationService notificationService;
@MockBean
private NotificationMapper notificationMapper;
@MockBean
private NotificationMapper notificationMapper;
@Test
void listNotifications() throws Exception {
Notification n = new Notification();
n.setId(1L);
n.setType(NotificationType.POST_VIEWED);
Post p = new Post();
p.setId(2L);
n.setPost(p);
n.setCreatedAt(LocalDateTime.now());
when(notificationService.listNotifications("alice", null, 0, 30))
.thenReturn(List.of(n));
@Test
void listNotifications() throws Exception {
Notification n = new Notification();
n.setId(1L);
n.setType(NotificationType.POST_VIEWED);
Post p = new Post();
p.setId(2L);
n.setPost(p);
n.setCreatedAt(LocalDateTime.now());
when(notificationService.listNotifications("alice", null, 0, 30)).thenReturn(List.of(n));
NotificationDto dto = new NotificationDto();
dto.setId(1L);
PostSummaryDto ps = new PostSummaryDto();
ps.setId(2L);
dto.setPost(ps);
when(notificationMapper.toDto(n)).thenReturn(dto);
NotificationDto dto = new NotificationDto();
dto.setId(1L);
PostSummaryDto ps = new PostSummaryDto();
ps.setId(2L);
dto.setPost(ps);
when(notificationMapper.toDto(n)).thenReturn(dto);
mockMvc.perform(get("/api/notifications")
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(1))
.andExpect(jsonPath("$[0].post.id").value(2));
}
mockMvc
.perform(
get("/api/notifications").principal(new UsernamePasswordAuthenticationToken("alice", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(1))
.andExpect(jsonPath("$[0].post.id").value(2));
}
@Test
void listUnreadNotifications() throws Exception {
Notification n = new Notification();
n.setId(5L);
n.setType(NotificationType.POST_VIEWED);
when(notificationService.listNotifications("alice", false, 0, 30))
.thenReturn(List.of(n));
@Test
void listUnreadNotifications() throws Exception {
Notification n = new Notification();
n.setId(5L);
n.setType(NotificationType.POST_VIEWED);
when(notificationService.listNotifications("alice", false, 0, 30)).thenReturn(List.of(n));
NotificationDto dto = new NotificationDto();
dto.setId(5L);
when(notificationMapper.toDto(n)).thenReturn(dto);
NotificationDto dto = new NotificationDto();
dto.setId(5L);
when(notificationMapper.toDto(n)).thenReturn(dto);
mockMvc.perform(get("/api/notifications/unread")
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(5));
}
mockMvc
.perform(
get("/api/notifications/unread").principal(
new UsernamePasswordAuthenticationToken("alice", "p")
)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(5));
}
@Test
void markReadEndpoint() throws Exception {
mockMvc.perform(post("/api/notifications/read")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"ids\":[1,2]}" )
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isOk());
@Test
void markReadEndpoint() throws Exception {
mockMvc
.perform(
post("/api/notifications/read")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"ids\":[1,2]}")
.principal(new UsernamePasswordAuthenticationToken("alice", "p"))
)
.andExpect(status().isOk());
verify(notificationService).markRead("alice", List.of(1L,2L));
}
verify(notificationService).markRead("alice", List.of(1L, 2L));
}
@Test
void unreadCountEndpoint() throws Exception {
when(notificationService.countUnread("alice")).thenReturn(3L);
@Test
void unreadCountEndpoint() throws Exception {
when(notificationService.countUnread("alice")).thenReturn(3L);
mockMvc.perform(get("/api/notifications/unread-count")
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.count").value(3));
}
mockMvc
.perform(
get("/api/notifications/unread-count").principal(
new UsernamePasswordAuthenticationToken("alice", "p")
)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.count").value(3));
}
}

View File

@@ -1,13 +1,20 @@
package com.openisle.controller;
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 com.openisle.config.CustomAccessDeniedHandler;
import com.openisle.config.SecurityConfig;
import com.openisle.service.PointService;
import com.openisle.mapper.PointHistoryMapper;
import com.openisle.service.JwtService;
import com.openisle.repository.UserRepository;
import com.openisle.model.User;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.JwtService;
import com.openisle.service.PointService;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -17,49 +24,47 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import java.util.Map;
import java.util.Optional;
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;
@WebMvcTest(PointHistoryController.class)
@AutoConfigureMockMvc
@Import({SecurityConfig.class, CustomAccessDeniedHandler.class})
@Import({ SecurityConfig.class, CustomAccessDeniedHandler.class })
class PointHistoryControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private JwtService jwtService;
@MockBean
private UserRepository userRepository;
@MockBean
private PointService pointService;
@MockBean
private PointHistoryMapper pointHistoryMapper;
@Autowired
private MockMvc mockMvc;
@Test
void trendReturnsSeries() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
List<Map<String, Object>> data = List.of(
Map.of("date", java.time.LocalDate.now().minusDays(1).toString(), "value", 100),
Map.of("date", java.time.LocalDate.now().toString(), "value", 110)
);
Mockito.when(pointService.trend(Mockito.eq("user"), Mockito.anyInt())).thenReturn(data);
@MockBean
private JwtService jwtService;
mockMvc.perform(get("/api/point-histories/trend").param("days", "2")
.header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(100))
.andExpect(jsonPath("$[1].value").value(110));
}
@MockBean
private UserRepository userRepository;
@MockBean
private PointService pointService;
@MockBean
private PointHistoryMapper pointHistoryMapper;
@Test
void trendReturnsSeries() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
List<Map<String, Object>> data = List.of(
Map.of("date", java.time.LocalDate.now().minusDays(1).toString(), "value", 100),
Map.of("date", java.time.LocalDate.now().toString(), "value", 110)
);
Mockito.when(pointService.trend(Mockito.eq("user"), Mockito.anyInt())).thenReturn(data);
mockMvc
.perform(
get("/api/point-histories/trend").param("days", "2").header("Authorization", "Bearer token")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(100))
.andExpect(jsonPath("$[1].value").value(110));
}
}

View File

@@ -1,5 +1,10 @@
package com.openisle.controller;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.openisle.mapper.CategoryMapper;
import com.openisle.mapper.CommentMapper;
import com.openisle.mapper.PostMapper;
@@ -8,6 +13,9 @@ import com.openisle.mapper.TagMapper;
import com.openisle.mapper.UserMapper;
import com.openisle.model.*;
import com.openisle.service.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
@@ -15,297 +23,356 @@ import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.util.ReflectionTestUtils;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import static org.mockito.ArgumentMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.mockito.Mockito.*;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(PostController.class)
@AutoConfigureMockMvc(addFilters = false)
@Import({PostMapper.class, CommentMapper.class, ReactionMapper.class,
UserMapper.class, TagMapper.class, CategoryMapper.class})
@Import(
{
PostMapper.class,
CommentMapper.class,
ReactionMapper.class,
UserMapper.class,
TagMapper.class,
CategoryMapper.class,
}
)
class PostControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private PostController postController;
@MockBean
private PostService postService;
@MockBean
private CommentService commentService;
@MockBean
private ReactionService reactionService;
@MockBean
private CaptchaService captchaService;
@MockBean
private DraftService draftService;
@MockBean
private LevelService levelService;
@MockBean
private SubscriptionService subscriptionService;
@MockBean
private UserVisitService userVisitService;
@MockBean
private PostReadService postReadService;
@MockBean
private MedalService medalService;
@MockBean
private com.openisle.repository.PollVoteRepository pollVoteRepository;
@Autowired
private MockMvc mockMvc;
@Test
void createAndGetPost() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
Post post = new Post();
post.setId(1L);
post.setTitle("t");
post.setContent("c");
post.setCreatedAt(LocalDateTime.now());
post.setAuthor(user);
post.setCategory(cat);
post.setTags(Set.of(tag));
@Autowired
private PostController postController;
when(postService.createPost(eq("alice"), eq(1L), eq("t"), eq("c"), eq(List.of(1L)),
isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull())).thenReturn(post);
when(postService.viewPost(eq(1L), any())).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
@MockBean
private PostService postService;
mockMvc.perform(post("/api/posts")
.contentType("application/json")
.content("{\"title\":\"t\",\"content\":\"c\",\"categoryId\":1,\"tagIds\":[1]}")
.principal(new UsernamePasswordAuthenticationToken("alice", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("t"))
.andExpect(jsonPath("$.comments").isArray())
.andExpect(jsonPath("$.comments").isEmpty())
.andExpect(jsonPath("$.author.username").value("alice"))
.andExpect(jsonPath("$.category.name").value("tech"))
.andExpect(jsonPath("$.tags[0].name").value("java"))
.andExpect(jsonPath("$.subscribed").value(false));
@MockBean
private CommentService commentService;
mockMvc.perform(get("/api/posts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.comments").isArray())
.andExpect(jsonPath("$.comments").isEmpty())
.andExpect(jsonPath("$.subscribed").value(false));
}
@MockBean
private ReactionService reactionService;
@Test
void updatePostReturnsDetailDto() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
Post post = new Post();
post.setId(1L);
post.setTitle("t2");
post.setContent("c2");
post.setCreatedAt(LocalDateTime.now());
post.setAuthor(user);
post.setCategory(cat);
post.setTags(Set.of(tag));
@MockBean
private CaptchaService captchaService;
when(postService.updatePost(eq(1L), eq("alice"), eq(1L), eq("t2"), eq("c2"), eq(List.of(1L)))).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
@MockBean
private DraftService draftService;
mockMvc.perform(put("/api/posts/1")
.contentType("application/json")
.content("{\"title\":\"t2\",\"content\":\"c2\",\"categoryId\":1,\"tagIds\":[1]}")
.principal(new UsernamePasswordAuthenticationToken("alice", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("t2"))
.andExpect(jsonPath("$.comments").isArray())
.andExpect(jsonPath("$.comments").isEmpty())
.andExpect(jsonPath("$.author.username").value("alice"));
}
@MockBean
private LevelService levelService;
@Test
void listPosts() throws Exception {
User user = new User();
user.setUsername("bob");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
Post post = new Post();
post.setId(2L);
post.setTitle("hello");
post.setContent("world");
post.setCreatedAt(LocalDateTime.now());
post.setAuthor(user);
post.setCategory(cat);
post.setTags(Set.of(tag));
@MockBean
private SubscriptionService subscriptionService;
when(postService.listPostsByCategories(null, null, null)).thenReturn(List.of(post));
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(anyLong())).thenReturn(List.of());
when(commentService.getLastCommentTime(anyLong())).thenReturn(null);
@MockBean
private UserVisitService userVisitService;
mockMvc.perform(get("/api/posts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("hello"))
.andExpect(jsonPath("$[0].comments").doesNotExist())
.andExpect(jsonPath("$[0].author.username").value("bob"))
.andExpect(jsonPath("$[0].category.name").value("tech"))
.andExpect(jsonPath("$[0].tags[0].name").value("java"))
.andExpect(jsonPath("$[0].subscribed").value(false));
}
@MockBean
private PostReadService postReadService;
@Test
void createPostRejectsInvalidCaptcha() throws Exception {
ReflectionTestUtils.setField(postController, "captchaEnabled", true);
ReflectionTestUtils.setField(postController, "postCaptchaEnabled", true);
when(captchaService.verify("bad")).thenReturn(false);
@MockBean
private MedalService medalService;
mockMvc.perform(post("/api/posts")
.contentType("application/json")
.content("{\"title\":\"t\",\"content\":\"c\",\"categoryId\":1,\"tagIds\":[1],\"captcha\":\"bad\"}")
.principal(new UsernamePasswordAuthenticationToken("alice", "p")))
.andExpect(status().isBadRequest());
@MockBean
private com.openisle.repository.PollVoteRepository pollVoteRepository;
verify(postService, never()).createPost(any(), any(), any(), any(), any(),
any(), any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
void createAndGetPost() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
Post post = new Post();
post.setId(1L);
post.setTitle("t");
post.setContent("c");
post.setCreatedAt(LocalDateTime.now());
post.setAuthor(user);
post.setCategory(cat);
post.setTags(Set.of(tag));
@Test
void getPostWithNestedData() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
Post post = new Post();
post.setId(1L);
post.setTitle("t");
post.setContent("c");
post.setCreatedAt(LocalDateTime.now());
post.setAuthor(user);
post.setCategory(cat);
post.setTags(Set.of(tag));
when(
postService.createPost(
eq("alice"),
eq(1L),
eq("t"),
eq("c"),
eq(List.of(1L)),
isNull(),
isNull(),
isNull(),
isNull(),
isNull(),
isNull(),
isNull(),
isNull(),
isNull()
)
).thenReturn(post);
when(postService.viewPost(eq(1L), any())).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
com.openisle.model.Comment comment = new com.openisle.model.Comment();
comment.setId(2L);
comment.setContent("hi");
comment.setCreatedAt(LocalDateTime.now());
comment.setAuthor(user);
comment.setPost(post);
mockMvc
.perform(
post("/api/posts")
.contentType("application/json")
.content("{\"title\":\"t\",\"content\":\"c\",\"categoryId\":1,\"tagIds\":[1]}")
.principal(new UsernamePasswordAuthenticationToken("alice", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("t"))
.andExpect(jsonPath("$.comments").isArray())
.andExpect(jsonPath("$.comments").isEmpty())
.andExpect(jsonPath("$.author.username").value("alice"))
.andExpect(jsonPath("$.category.name").value("tech"))
.andExpect(jsonPath("$.tags[0].name").value("java"))
.andExpect(jsonPath("$.subscribed").value(false));
com.openisle.model.Comment reply = new com.openisle.model.Comment();
reply.setId(3L);
reply.setContent("reply");
reply.setCreatedAt(LocalDateTime.now());
reply.setAuthor(user);
reply.setPost(post);
mockMvc
.perform(get("/api/posts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.comments").isArray())
.andExpect(jsonPath("$.comments").isEmpty())
.andExpect(jsonPath("$.subscribed").value(false));
}
com.openisle.model.Reaction pr = new com.openisle.model.Reaction();
pr.setId(10L);
pr.setUser(user);
pr.setPost(post);
pr.setType(com.openisle.model.ReactionType.LIKE);
@Test
void updatePostReturnsDetailDto() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
Post post = new Post();
post.setId(1L);
post.setTitle("t2");
post.setContent("c2");
post.setCreatedAt(LocalDateTime.now());
post.setAuthor(user);
post.setCategory(cat);
post.setTags(Set.of(tag));
com.openisle.model.Reaction cr = new com.openisle.model.Reaction();
cr.setId(11L);
cr.setUser(user);
cr.setComment(comment);
cr.setType(com.openisle.model.ReactionType.LIKE);
when(
postService.updatePost(eq(1L), eq("alice"), eq(1L), eq("t2"), eq("c2"), eq(List.of(1L)))
).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
when(postService.viewPost(eq(1L), any())).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of(comment));
when(commentService.getReplies(2L)).thenReturn(List.of(reply));
when(commentService.getReplies(3L)).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of(pr));
when(reactionService.getReactionsForComment(2L)).thenReturn(List.of(cr));
when(reactionService.getReactionsForComment(3L)).thenReturn(List.of());
mockMvc
.perform(
put("/api/posts/1")
.contentType("application/json")
.content("{\"title\":\"t2\",\"content\":\"c2\",\"categoryId\":1,\"tagIds\":[1]}")
.principal(new UsernamePasswordAuthenticationToken("alice", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("t2"))
.andExpect(jsonPath("$.comments").isArray())
.andExpect(jsonPath("$.comments").isEmpty())
.andExpect(jsonPath("$.author.username").value("alice"));
}
mockMvc.perform(get("/api/posts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.reactions[0].id").value(10))
.andExpect(jsonPath("$.comments[0].replies[0].id").value(3))
.andExpect(jsonPath("$.comments[0].reactions[0].id").value(11))
.andExpect(jsonPath("$.author.username").value("alice"))
.andExpect(jsonPath("$.category.name").value("tech"))
.andExpect(jsonPath("$.tags[0].name").value("java"));
}
@Test
void listPosts() throws Exception {
User user = new User();
user.setUsername("bob");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
Post post = new Post();
post.setId(2L);
post.setTitle("hello");
post.setContent("world");
post.setCreatedAt(LocalDateTime.now());
post.setAuthor(user);
post.setCategory(cat);
post.setTags(Set.of(tag));
@Test
void getPostSubscriptionStatus() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Post post = new Post();
post.setId(1L);
post.setTitle("t");
post.setContent("c");
post.setCreatedAt(LocalDateTime.now());
post.setAuthor(user);
post.setCategory(cat);
post.setTags(Set.of());
when(postService.listPostsByCategories(null, null, null)).thenReturn(List.of(post));
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(anyLong())).thenReturn(List.of());
when(commentService.getLastCommentTime(anyLong())).thenReturn(null);
when(postService.viewPost(eq(1L), any())).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
when(subscriptionService.isPostSubscribed("alice", 1L)).thenReturn(true);
mockMvc
.perform(get("/api/posts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("hello"))
.andExpect(jsonPath("$[0].comments").doesNotExist())
.andExpect(jsonPath("$[0].author.username").value("bob"))
.andExpect(jsonPath("$[0].category.name").value("tech"))
.andExpect(jsonPath("$[0].tags[0].name").value("java"))
.andExpect(jsonPath("$[0].subscribed").value(false));
}
mockMvc.perform(get("/api/posts/1").principal(new UsernamePasswordAuthenticationToken("alice", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.subscribed").value(true));
@Test
void createPostRejectsInvalidCaptcha() throws Exception {
ReflectionTestUtils.setField(postController, "captchaEnabled", true);
ReflectionTestUtils.setField(postController, "postCaptchaEnabled", true);
when(captchaService.verify("bad")).thenReturn(false);
mockMvc.perform(get("/api/posts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.subscribed").value(false));
}
mockMvc
.perform(
post("/api/posts")
.contentType("application/json")
.content(
"{\"title\":\"t\",\"content\":\"c\",\"categoryId\":1,\"tagIds\":[1],\"captcha\":\"bad\"}"
)
.principal(new UsernamePasswordAuthenticationToken("alice", "p"))
)
.andExpect(status().isBadRequest());
verify(postService, never()).createPost(
any(),
any(),
any(),
any(),
any(),
any(),
any(),
any(),
any(),
any(),
any(),
any(),
any(),
any()
);
}
@Test
void getPostWithNestedData() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Tag tag = new Tag();
tag.setId(1L);
tag.setName("java");
tag.setDescription("Java programming language");
tag.setIcon("java-icon");
Post post = new Post();
post.setId(1L);
post.setTitle("t");
post.setContent("c");
post.setCreatedAt(LocalDateTime.now());
post.setAuthor(user);
post.setCategory(cat);
post.setTags(Set.of(tag));
com.openisle.model.Comment comment = new com.openisle.model.Comment();
comment.setId(2L);
comment.setContent("hi");
comment.setCreatedAt(LocalDateTime.now());
comment.setAuthor(user);
comment.setPost(post);
com.openisle.model.Comment reply = new com.openisle.model.Comment();
reply.setId(3L);
reply.setContent("reply");
reply.setCreatedAt(LocalDateTime.now());
reply.setAuthor(user);
reply.setPost(post);
com.openisle.model.Reaction pr = new com.openisle.model.Reaction();
pr.setId(10L);
pr.setUser(user);
pr.setPost(post);
pr.setType(com.openisle.model.ReactionType.LIKE);
com.openisle.model.Reaction cr = new com.openisle.model.Reaction();
cr.setId(11L);
cr.setUser(user);
cr.setComment(comment);
cr.setType(com.openisle.model.ReactionType.LIKE);
when(postService.viewPost(eq(1L), any())).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of(comment));
when(commentService.getReplies(2L)).thenReturn(List.of(reply));
when(commentService.getReplies(3L)).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of(pr));
when(reactionService.getReactionsForComment(2L)).thenReturn(List.of(cr));
when(reactionService.getReactionsForComment(3L)).thenReturn(List.of());
mockMvc
.perform(get("/api/posts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.reactions[0].id").value(10))
.andExpect(jsonPath("$.comments[0].replies[0].id").value(3))
.andExpect(jsonPath("$.comments[0].reactions[0].id").value(11))
.andExpect(jsonPath("$.author.username").value("alice"))
.andExpect(jsonPath("$.category.name").value("tech"))
.andExpect(jsonPath("$.tags[0].name").value("java"));
}
@Test
void getPostSubscriptionStatus() throws Exception {
User user = new User();
user.setUsername("alice");
Category cat = new Category();
cat.setId(1L);
cat.setName("tech");
cat.setDescription("Technology category");
cat.setIcon("tech-icon");
Post post = new Post();
post.setId(1L);
post.setTitle("t");
post.setContent("c");
post.setCreatedAt(LocalDateTime.now());
post.setAuthor(user);
post.setCategory(cat);
post.setTags(Set.of());
when(postService.viewPost(eq(1L), any())).thenReturn(post);
when(commentService.getCommentsForPost(eq(1L), any())).thenReturn(List.of());
when(commentService.getParticipants(anyLong(), anyInt())).thenReturn(List.of());
when(reactionService.getReactionsForPost(1L)).thenReturn(List.of());
when(commentService.getLastCommentTime(1L)).thenReturn(null);
when(subscriptionService.isPostSubscribed("alice", 1L)).thenReturn(true);
mockMvc
.perform(get("/api/posts/1").principal(new UsernamePasswordAuthenticationToken("alice", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.subscribed").value(true));
mockMvc
.perform(get("/api/posts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.subscribed").value(false));
}
}

View File

@@ -1,5 +1,8 @@
package com.openisle.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.openisle.service.PushSubscriptionService;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
@@ -11,26 +14,26 @@ import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(PushSubscriptionController.class)
@AutoConfigureMockMvc(addFilters = false)
class PushSubscriptionControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private MockMvc mockMvc;
@MockBean
private PushSubscriptionService pushSubscriptionService;
@MockBean
private PushSubscriptionService pushSubscriptionService;
@Test
void subscribeEndpoint() throws Exception {
mockMvc.perform(post("/api/push/subscribe")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"endpoint\":\"e\",\"p256dh\":\"p\",\"auth\":\"a\"}")
.principal(new UsernamePasswordAuthenticationToken("u","p")))
.andExpect(status().isOk());
Mockito.verify(pushSubscriptionService).saveSubscription("u","e","p","a");
}
@Test
void subscribeEndpoint() throws Exception {
mockMvc
.perform(
post("/api/push/subscribe")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"endpoint\":\"e\",\"p256dh\":\"p\",\"auth\":\"a\"}")
.principal(new UsernamePasswordAuthenticationToken("u", "p"))
)
.andExpect(status().isOk());
Mockito.verify(pushSubscriptionService).saveSubscription("u", "e", "p", "a");
}
}

View File

@@ -1,14 +1,20 @@
package com.openisle.controller;
import static org.mockito.ArgumentMatchers.eq;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.openisle.mapper.ReactionMapper;
import com.openisle.model.Comment;
import com.openisle.model.Message;
import com.openisle.model.Post;
import com.openisle.model.Reaction;
import com.openisle.model.ReactionType;
import com.openisle.model.User;
import com.openisle.model.Message;
import com.openisle.service.ReactionService;
import com.openisle.service.LevelService;
import com.openisle.mapper.ReactionMapper;
import com.openisle.service.ReactionService;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -19,91 +25,103 @@ import org.springframework.context.annotation.Import;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.ArgumentMatchers.eq;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
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;
@WebMvcTest(ReactionController.class)
@AutoConfigureMockMvc(addFilters = false)
@Import(ReactionMapper.class)
class ReactionControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private ReactionService reactionService;
@MockBean
private LevelService levelService;
@Autowired
private MockMvc mockMvc;
@Test
void reactToPost() throws Exception {
User user = new User();
user.setUsername("u1");
Post post = new Post();
post.setId(1L);
Reaction reaction = new Reaction();
reaction.setId(1L);
reaction.setUser(user);
reaction.setPost(post);
reaction.setType(ReactionType.LIKE);
Mockito.when(reactionService.reactToPost(eq("u1"), eq(1L), eq(ReactionType.LIKE))).thenReturn(reaction);
@MockBean
private ReactionService reactionService;
mockMvc.perform(post("/api/posts/1/reactions")
.contentType("application/json")
.content("{\"type\":\"LIKE\"}")
.principal(new UsernamePasswordAuthenticationToken("u1", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.postId").value(1));
}
@MockBean
private LevelService levelService;
@Test
void reactToComment() throws Exception {
User user = new User();
user.setUsername("u2");
Comment comment = new Comment();
comment.setId(2L);
Reaction reaction = new Reaction();
reaction.setId(2L);
reaction.setUser(user);
reaction.setComment(comment);
reaction.setType(ReactionType.RECOMMEND);
Mockito.when(reactionService.reactToComment(eq("u2"), eq(2L), eq(ReactionType.RECOMMEND))).thenReturn(reaction);
@Test
void reactToPost() throws Exception {
User user = new User();
user.setUsername("u1");
Post post = new Post();
post.setId(1L);
Reaction reaction = new Reaction();
reaction.setId(1L);
reaction.setUser(user);
reaction.setPost(post);
reaction.setType(ReactionType.LIKE);
Mockito.when(reactionService.reactToPost(eq("u1"), eq(1L), eq(ReactionType.LIKE))).thenReturn(
reaction
);
mockMvc.perform(post("/api/comments/2/reactions")
.contentType("application/json")
.content("{\"type\":\"RECOMMEND\"}")
.principal(new UsernamePasswordAuthenticationToken("u2", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.commentId").value(2));
}
mockMvc
.perform(
post("/api/posts/1/reactions")
.contentType("application/json")
.content("{\"type\":\"LIKE\"}")
.principal(new UsernamePasswordAuthenticationToken("u1", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.postId").value(1));
}
@Test
void reactToMessage() throws Exception {
User user = new User();
user.setUsername("u3");
Message message = new Message();
message.setId(3L);
Reaction reaction = new Reaction();
reaction.setId(3L);
reaction.setUser(user);
reaction.setMessage(message);
reaction.setType(ReactionType.LIKE);
Mockito.when(reactionService.reactToMessage(eq("u3"), eq(3L), eq(ReactionType.LIKE))).thenReturn(reaction);
@Test
void reactToComment() throws Exception {
User user = new User();
user.setUsername("u2");
Comment comment = new Comment();
comment.setId(2L);
Reaction reaction = new Reaction();
reaction.setId(2L);
reaction.setUser(user);
reaction.setComment(comment);
reaction.setType(ReactionType.RECOMMEND);
Mockito.when(
reactionService.reactToComment(eq("u2"), eq(2L), eq(ReactionType.RECOMMEND))
).thenReturn(reaction);
mockMvc.perform(post("/api/messages/3/reactions")
.contentType("application/json")
.content("{\"type\":\"LIKE\"}")
.principal(new UsernamePasswordAuthenticationToken("u3", "p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.messageId").value(3));
}
mockMvc
.perform(
post("/api/comments/2/reactions")
.contentType("application/json")
.content("{\"type\":\"RECOMMEND\"}")
.principal(new UsernamePasswordAuthenticationToken("u2", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.commentId").value(2));
}
@Test
void listReactionTypes() throws Exception {
mockMvc.perform(get("/api/reaction-types"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0]").value("LIKE"));
}
@Test
void reactToMessage() throws Exception {
User user = new User();
user.setUsername("u3");
Message message = new Message();
message.setId(3L);
Reaction reaction = new Reaction();
reaction.setId(3L);
reaction.setUser(user);
reaction.setMessage(message);
reaction.setType(ReactionType.LIKE);
Mockito.when(
reactionService.reactToMessage(eq("u3"), eq(3L), eq(ReactionType.LIKE))
).thenReturn(reaction);
mockMvc
.perform(
post("/api/messages/3/reactions")
.contentType("application/json")
.content("{\"type\":\"LIKE\"}")
.principal(new UsernamePasswordAuthenticationToken("u3", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.messageId").value(3));
}
@Test
void listReactionTypes() throws Exception {
mockMvc
.perform(get("/api/reaction-types"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0]").value("LIKE"));
}
}

View File

@@ -1,14 +1,18 @@
package com.openisle.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.openisle.dto.PostSummaryDto;
import com.openisle.dto.UserDto;
import com.openisle.mapper.PostMapper;
import com.openisle.mapper.UserMapper;
import com.openisle.model.Comment;
import com.openisle.model.Post;
import com.openisle.model.User;
import com.openisle.model.PostStatus;
import com.openisle.model.User;
import com.openisle.service.SearchService;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -17,94 +21,98 @@ 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.util.List;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(SearchController.class)
@AutoConfigureMockMvc(addFilters = false)
class SearchControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private SearchService searchService;
@MockBean
private UserMapper userMapper;
@MockBean
private PostMapper postMapper;
@Autowired
private MockMvc mockMvc;
@Test
void userSearchEndpoint() throws Exception {
User user = new User();
user.setId(1L);
user.setUsername("alice");
Mockito.when(searchService.searchUsers("ali")).thenReturn(List.of(user));
UserDto userDto = new UserDto();
userDto.setId(1L);
userDto.setUsername("alice");
Mockito.when(userMapper.toDto(user)).thenReturn(userDto);
@MockBean
private SearchService searchService;
mockMvc.perform(get("/api/search/users").param("keyword", "ali"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].username").value("alice"));
}
@MockBean
private UserMapper userMapper;
@Test
void globalSearchAggregatesTypes() throws Exception {
User u = new User();
u.setId(1L);
u.setUsername("bob");
Post p = new Post();
p.setId(2L);
p.setTitle("hello");
p.setStatus(PostStatus.PUBLISHED);
Comment c = new Comment();
c.setId(3L);
c.setContent("nice");
Mockito.when(searchService.globalSearch("n")).thenReturn(List.of(
new SearchService.SearchResult("user", 1L, "bob", null, null, null),
new SearchService.SearchResult("post", 2L, "hello", null, null, null),
new SearchService.SearchResult("comment", 3L, "nice", null, null, null)
));
@MockBean
private PostMapper postMapper;
mockMvc.perform(get("/api/search/global").param("keyword", "n"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].type").value("user"))
.andExpect(jsonPath("$[1].type").value("post"))
.andExpect(jsonPath("$[2].type").value("comment"));
}
@Test
void userSearchEndpoint() throws Exception {
User user = new User();
user.setId(1L);
user.setUsername("alice");
Mockito.when(searchService.searchUsers("ali")).thenReturn(List.of(user));
UserDto userDto = new UserDto();
userDto.setId(1L);
userDto.setUsername("alice");
Mockito.when(userMapper.toDto(user)).thenReturn(userDto);
@Test
void searchPostsByTitle() throws Exception {
Post p = new Post();
p.setId(2L);
p.setTitle("spring");
Mockito.when(searchService.searchPostsByTitle("spr")).thenReturn(List.of(p));
PostSummaryDto summaryDto1 = new PostSummaryDto();
summaryDto1.setId(2L);
summaryDto1.setTitle("spring");
Mockito.when(postMapper.toSummaryDto(p)).thenReturn(summaryDto1);
mockMvc
.perform(get("/api/search/users").param("keyword", "ali"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].username").value("alice"));
}
mockMvc.perform(get("/api/search/posts/title").param("keyword", "spr"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("spring"));
}
@Test
void globalSearchAggregatesTypes() throws Exception {
User u = new User();
u.setId(1L);
u.setUsername("bob");
Post p = new Post();
p.setId(2L);
p.setTitle("hello");
p.setStatus(PostStatus.PUBLISHED);
Comment c = new Comment();
c.setId(3L);
c.setContent("nice");
Mockito.when(searchService.globalSearch("n")).thenReturn(
List.of(
new SearchService.SearchResult("user", 1L, "bob", null, null, null),
new SearchService.SearchResult("post", 2L, "hello", null, null, null),
new SearchService.SearchResult("comment", 3L, "nice", null, null, null)
)
);
@Test
void searchPosts() throws Exception {
Post p = new Post();
p.setId(5L);
p.setTitle("hello");
Mockito.when(searchService.searchPosts("he")).thenReturn(List.of(p));
PostSummaryDto summaryDto2 = new PostSummaryDto();
summaryDto2.setId(5L);
summaryDto2.setTitle("hello");
Mockito.when(postMapper.toSummaryDto(p)).thenReturn(summaryDto2);
mockMvc
.perform(get("/api/search/global").param("keyword", "n"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].type").value("user"))
.andExpect(jsonPath("$[1].type").value("post"))
.andExpect(jsonPath("$[2].type").value("comment"));
}
mockMvc.perform(get("/api/search/posts").param("keyword", "he"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(5));
}
@Test
void searchPostsByTitle() throws Exception {
Post p = new Post();
p.setId(2L);
p.setTitle("spring");
Mockito.when(searchService.searchPostsByTitle("spr")).thenReturn(List.of(p));
PostSummaryDto summaryDto1 = new PostSummaryDto();
summaryDto1.setId(2L);
summaryDto1.setTitle("spring");
Mockito.when(postMapper.toSummaryDto(p)).thenReturn(summaryDto1);
mockMvc
.perform(get("/api/search/posts/title").param("keyword", "spr"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("spring"));
}
@Test
void searchPosts() throws Exception {
Post p = new Post();
p.setId(5L);
p.setTitle("hello");
Mockito.when(searchService.searchPosts("he")).thenReturn(List.of(p));
PostSummaryDto summaryDto2 = new PostSummaryDto();
summaryDto2.setId(5L);
summaryDto2.setTitle("hello");
Mockito.when(postMapper.toSummaryDto(p)).thenReturn(summaryDto2);
mockMvc
.perform(get("/api/search/posts").param("keyword", "he"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(5));
}
}

View File

@@ -1,13 +1,18 @@
package com.openisle.controller;
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 com.openisle.config.CustomAccessDeniedHandler;
import com.openisle.config.SecurityConfig;
import com.openisle.service.JwtService;
import com.openisle.repository.UserRepository;
import com.openisle.service.UserVisitService;
import com.openisle.service.StatService;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import com.openisle.service.JwtService;
import com.openisle.service.StatService;
import com.openisle.service.UserVisitService;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -17,121 +22,132 @@ import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Optional;
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;
@WebMvcTest(StatController.class)
@AutoConfigureMockMvc
@Import({SecurityConfig.class, CustomAccessDeniedHandler.class})
@Import({ SecurityConfig.class, CustomAccessDeniedHandler.class })
class StatControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private JwtService jwtService;
@MockBean
private UserRepository userRepository;
@MockBean
private UserVisitService userVisitService;
@MockBean
private StatService statService;
@Autowired
private MockMvc mockMvc;
@Test
void dauReturnsCount() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
Mockito.when(userVisitService.countDau(Mockito.any())).thenReturn(3L);
@MockBean
private JwtService jwtService;
mockMvc.perform(get("/api/stats/dau").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.dau").value(3));
}
@MockBean
private UserRepository userRepository;
@Test
void dauRangeReturnsSeries() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
java.util.Map<java.time.LocalDate, Long> map = new java.util.LinkedHashMap<>();
map.put(java.time.LocalDate.now().minusDays(1), 1L);
map.put(java.time.LocalDate.now(), 2L);
Mockito.when(userVisitService.countDauRange(Mockito.any(), Mockito.any())).thenReturn(map);
@MockBean
private UserVisitService userVisitService;
mockMvc.perform(get("/api/stats/dau-range").param("days", "2").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(1))
.andExpect(jsonPath("$[1].value").value(2));
}
@MockBean
private StatService statService;
@Test
void newUsersRangeReturnsSeries() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
java.util.Map<java.time.LocalDate, Long> map = new java.util.LinkedHashMap<>();
map.put(java.time.LocalDate.now().minusDays(1), 5L);
map.put(java.time.LocalDate.now(), 6L);
Mockito.when(statService.countNewUsersRange(Mockito.any(), Mockito.any())).thenReturn(map);
@Test
void dauReturnsCount() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
Mockito.when(userVisitService.countDau(Mockito.any())).thenReturn(3L);
mockMvc.perform(get("/api/stats/new-users-range").param("days", "2").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(5))
.andExpect(jsonPath("$[1].value").value(6));
}
mockMvc
.perform(get("/api/stats/dau").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.dau").value(3));
}
@Test
void postsRangeReturnsSeries() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
java.util.Map<java.time.LocalDate, Long> map = new java.util.LinkedHashMap<>();
map.put(java.time.LocalDate.now().minusDays(1), 7L);
map.put(java.time.LocalDate.now(), 8L);
Mockito.when(statService.countPostsRange(Mockito.any(), Mockito.any())).thenReturn(map);
@Test
void dauRangeReturnsSeries() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
java.util.Map<java.time.LocalDate, Long> map = new java.util.LinkedHashMap<>();
map.put(java.time.LocalDate.now().minusDays(1), 1L);
map.put(java.time.LocalDate.now(), 2L);
Mockito.when(userVisitService.countDauRange(Mockito.any(), Mockito.any())).thenReturn(map);
mockMvc.perform(get("/api/stats/posts-range").param("days", "2").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(7))
.andExpect(jsonPath("$[1].value").value(8));
}
mockMvc
.perform(
get("/api/stats/dau-range").param("days", "2").header("Authorization", "Bearer token")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(1))
.andExpect(jsonPath("$[1].value").value(2));
}
@Test
void commentsRangeReturnsSeries() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
java.util.Map<java.time.LocalDate, Long> map = new java.util.LinkedHashMap<>();
map.put(java.time.LocalDate.now().minusDays(1), 9L);
map.put(java.time.LocalDate.now(), 10L);
Mockito.when(statService.countCommentsRange(Mockito.any(), Mockito.any())).thenReturn(map);
@Test
void newUsersRangeReturnsSeries() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
java.util.Map<java.time.LocalDate, Long> map = new java.util.LinkedHashMap<>();
map.put(java.time.LocalDate.now().minusDays(1), 5L);
map.put(java.time.LocalDate.now(), 6L);
Mockito.when(statService.countNewUsersRange(Mockito.any(), Mockito.any())).thenReturn(map);
mockMvc.perform(get("/api/stats/comments-range").param("days", "2").header("Authorization", "Bearer token"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(9))
.andExpect(jsonPath("$[1].value").value(10));
}
mockMvc
.perform(
get("/api/stats/new-users-range").param("days", "2").header("Authorization", "Bearer token")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(5))
.andExpect(jsonPath("$[1].value").value(6));
}
@Test
void postsRangeReturnsSeries() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
java.util.Map<java.time.LocalDate, Long> map = new java.util.LinkedHashMap<>();
map.put(java.time.LocalDate.now().minusDays(1), 7L);
map.put(java.time.LocalDate.now(), 8L);
Mockito.when(statService.countPostsRange(Mockito.any(), Mockito.any())).thenReturn(map);
mockMvc
.perform(
get("/api/stats/posts-range").param("days", "2").header("Authorization", "Bearer token")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(7))
.andExpect(jsonPath("$[1].value").value(8));
}
@Test
void commentsRangeReturnsSeries() throws Exception {
Mockito.when(jwtService.validateAndGetSubject("token")).thenReturn("user");
User user = new User();
user.setUsername("user");
user.setPassword("p");
user.setEmail("u@example.com");
user.setRole(Role.USER);
Mockito.when(userRepository.findByUsername("user")).thenReturn(Optional.of(user));
java.util.Map<java.time.LocalDate, Long> map = new java.util.LinkedHashMap<>();
map.put(java.time.LocalDate.now().minusDays(1), 9L);
map.put(java.time.LocalDate.now(), 10L);
Mockito.when(statService.countCommentsRange(Mockito.any(), Mockito.any())).thenReturn(map);
mockMvc
.perform(
get("/api/stats/comments-range").param("days", "2").header("Authorization", "Bearer token")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].value").value(9))
.andExpect(jsonPath("$[1].value").value(10));
}
}

View File

@@ -1,11 +1,17 @@
package com.openisle.controller;
import com.openisle.mapper.TagMapper;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.openisle.mapper.PostMapper;
import com.openisle.mapper.TagMapper;
import com.openisle.model.Tag;
import com.openisle.repository.UserRepository;
import com.openisle.service.TagService;
import com.openisle.service.PostService;
import com.openisle.service.TagService;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -16,94 +22,102 @@ import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(TagController.class)
@AutoConfigureMockMvc(addFilters = false)
@Import(TagMapper.class)
class TagControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private TagService tagService;
@Autowired
private MockMvc mockMvc;
@MockBean
private PostService postService;
@MockBean
private TagService tagService;
@MockBean
private UserRepository userRepository;
@MockBean
private PostService postService;
@MockBean
private PostMapper postMapper;
@MockBean
private UserRepository userRepository;
@Test
void createAndGetTag() throws Exception {
Tag t = new Tag();
t.setId(1L);
t.setName("java");
t.setDescription("d");
t.setIcon("i");
t.setSmallIcon("s1");
Mockito.when(tagService.createTag(eq("java"), eq("d"), eq("i"), eq("s1"), eq(true), isNull())).thenReturn(t);
Mockito.when(tagService.getTag(1L)).thenReturn(t);
@MockBean
private PostMapper postMapper;
mockMvc.perform(post("/api/tags")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"java\",\"description\":\"d\",\"icon\":\"i\",\"smallIcon\":\"s1\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("java"))
.andExpect(jsonPath("$.description").value("d"))
.andExpect(jsonPath("$.icon").value("i"))
.andExpect(jsonPath("$.smallIcon").value("s1"));
@Test
void createAndGetTag() throws Exception {
Tag t = new Tag();
t.setId(1L);
t.setName("java");
t.setDescription("d");
t.setIcon("i");
t.setSmallIcon("s1");
Mockito.when(
tagService.createTag(eq("java"), eq("d"), eq("i"), eq("s1"), eq(true), isNull())
).thenReturn(t);
Mockito.when(tagService.getTag(1L)).thenReturn(t);
mockMvc.perform(get("/api/tags/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1));
}
mockMvc
.perform(
post("/api/tags")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"java\",\"description\":\"d\",\"icon\":\"i\",\"smallIcon\":\"s1\"}")
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("java"))
.andExpect(jsonPath("$.description").value("d"))
.andExpect(jsonPath("$.icon").value("i"))
.andExpect(jsonPath("$.smallIcon").value("s1"));
@Test
void listTags() throws Exception {
Tag t = new Tag();
t.setId(2L);
t.setName("spring");
t.setDescription("d2");
t.setIcon("i2");
t.setSmallIcon("s2");
Mockito.when(tagService.searchTags(null)).thenReturn(List.of(t));
mockMvc
.perform(get("/api/tags/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1));
}
mockMvc.perform(get("/api/tags"))
.andExpect(status().isOk())
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].name").value("spring"))
.andExpect(jsonPath("$[0].description").value("d2"))
.andExpect(jsonPath("$[0].icon").value("i2"))
.andExpect(jsonPath("$[0].smallIcon").value("s2"));
}
@Test
void listTags() throws Exception {
Tag t = new Tag();
t.setId(2L);
t.setName("spring");
t.setDescription("d2");
t.setIcon("i2");
t.setSmallIcon("s2");
Mockito.when(tagService.searchTags(null)).thenReturn(List.of(t));
@Test
void updateTag() throws Exception {
Tag t = new Tag();
t.setId(3L);
t.setName("java");
t.setDescription("d3");
t.setIcon("i3");
t.setSmallIcon("s3");
Mockito.when(tagService.updateTag(eq(3L), eq("java"), eq("d3"), eq("i3"), eq("s3"))).thenReturn(t);
mockMvc
.perform(get("/api/tags"))
.andExpect(status().isOk())
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].name").value("spring"))
.andExpect(jsonPath("$[0].description").value("d2"))
.andExpect(jsonPath("$[0].icon").value("i2"))
.andExpect(jsonPath("$[0].smallIcon").value("s2"));
}
mockMvc.perform(put("/api/tags/3")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"java\",\"description\":\"d3\",\"icon\":\"i3\",\"smallIcon\":\"s3\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(3))
.andExpect(jsonPath("$.name").value("java"))
.andExpect(jsonPath("$.description").value("d3"))
.andExpect(jsonPath("$.icon").value("i3"))
.andExpect(jsonPath("$.smallIcon").value("s3"));
}
@Test
void updateTag() throws Exception {
Tag t = new Tag();
t.setId(3L);
t.setName("java");
t.setDescription("d3");
t.setIcon("i3");
t.setSmallIcon("s3");
Mockito.when(tagService.updateTag(eq(3L), eq("java"), eq("d3"), eq("i3"), eq("s3"))).thenReturn(
t
);
mockMvc
.perform(
put("/api/tags/3")
.contentType(MediaType.APPLICATION_JSON)
.content(
"{\"name\":\"java\",\"description\":\"d3\",\"icon\":\"i3\",\"smallIcon\":\"s3\"}"
)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(3))
.andExpect(jsonPath("$.name").value("java"))
.andExpect(jsonPath("$.description").value("d3"))
.andExpect(jsonPath("$.icon").value("i3"))
.andExpect(jsonPath("$.smallIcon").value("s3"));
}
}

View File

@@ -1,12 +1,18 @@
package com.openisle.controller;
import com.openisle.model.User;
import com.openisle.service.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.openisle.dto.CommentInfoDto;
import com.openisle.dto.PostMetaDto;
import com.openisle.dto.UserDto;
import com.openisle.mapper.TagMapper;
import com.openisle.mapper.UserMapper;
import com.openisle.dto.UserDto;
import com.openisle.dto.PostMetaDto;
import com.openisle.dto.CommentInfoDto;
import com.openisle.model.User;
import com.openisle.service.*;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
@@ -18,217 +24,254 @@ import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(UserController.class)
@AutoConfigureMockMvc(addFilters = false)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private ReactionService reactionService;
@MockBean
private SubscriptionService subscriptionService;
@MockBean
private UserService userService;
@MockBean
private ImageUploader imageUploader;
@MockBean
private PostService postService;
@MockBean
private CommentService commentService;
@MockBean
private LevelService levelService;
@MockBean
private TagService tagService;
@MockBean
private JwtService jwtService;
@MockBean
private UserMapper userMapper;
@MockBean
private TagMapper tagMapper;
@Autowired
private MockMvc mockMvc;
@Test
void getCurrentUser() throws Exception {
User u = new User();
u.setId(1L);
u.setUsername("alice");
u.setEmail("a@b.com");
u.setAvatar("http://x/avatar.png");
Mockito.when(userService.findByUsername("alice")).thenReturn(Optional.of(u));
UserDto dto = new UserDto();
dto.setId(1L);
dto.setUsername("alice");
dto.setAvatar("http://x/avatar.png");
Mockito.when(userMapper.toDto(eq(u), any())).thenReturn(dto);
@MockBean
private ReactionService reactionService;
mockMvc.perform(get("/api/users/me").principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.avatar").value("http://x/avatar.png"));
}
@MockBean
private SubscriptionService subscriptionService;
@Test
void uploadAvatar() throws Exception {
MockMultipartFile file = new MockMultipartFile("file", "a.png", MediaType.IMAGE_PNG_VALUE, "img".getBytes());
Mockito.when(imageUploader.upload(any(), eq("a.png"))).thenReturn(java.util.concurrent.CompletableFuture.completedFuture("http://img/a.png"));
@MockBean
private UserService userService;
mockMvc.perform(multipart("/api/users/me/avatar").file(file).principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isOk())
.andExpect(jsonPath("$.url").value("http://img/a.png"));
@MockBean
private ImageUploader imageUploader;
Mockito.verify(userService).updateAvatar("alice", "http://img/a.png");
}
@MockBean
private PostService postService;
@Test
void uploadAvatarRejectsNonImage() throws Exception {
MockMultipartFile file = new MockMultipartFile("file", "a.txt", MediaType.TEXT_PLAIN_VALUE, "text".getBytes());
@MockBean
private CommentService commentService;
mockMvc.perform(multipart("/api/users/me/avatar").file(file).principal(new UsernamePasswordAuthenticationToken("alice","p")))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.error").value("File is not an image"));
@MockBean
private LevelService levelService;
Mockito.verify(imageUploader, Mockito.never()).upload(any(), any());
}
@MockBean
private TagService tagService;
@Test
void getUserByName() throws Exception {
User u = new User();
u.setId(2L);
u.setUsername("bob");
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(u));
UserDto dto = new UserDto();
dto.setId(2L);
dto.setUsername("bob");
Mockito.when(userMapper.toDto(eq(u), any())).thenReturn(dto);
@MockBean
private JwtService jwtService;
mockMvc.perform(get("/api/users/bob"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(2));
}
@MockBean
private UserMapper userMapper;
@Test
void listUserPosts() throws Exception {
User user = new User();
user.setUsername("bob");
com.openisle.model.Category cat = new com.openisle.model.Category();
cat.setName("tech");
com.openisle.model.Post post = new com.openisle.model.Post();
post.setId(3L);
post.setTitle("hello");
post.setCreatedAt(java.time.LocalDateTime.now());
post.setCategory(cat);
post.setAuthor(user);
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
Mockito.when(postService.getRecentPostsByUser("bob", 10)).thenReturn(java.util.List.of(post));
PostMetaDto meta = new PostMetaDto();
meta.setId(3L);
meta.setTitle("hello");
Mockito.when(userMapper.toMetaDto(post)).thenReturn(meta);
@MockBean
private TagMapper tagMapper;
mockMvc.perform(get("/api/users/bob/posts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("hello"));
}
@Test
void getCurrentUser() throws Exception {
User u = new User();
u.setId(1L);
u.setUsername("alice");
u.setEmail("a@b.com");
u.setAvatar("http://x/avatar.png");
Mockito.when(userService.findByUsername("alice")).thenReturn(Optional.of(u));
UserDto dto = new UserDto();
dto.setId(1L);
dto.setUsername("alice");
dto.setAvatar("http://x/avatar.png");
Mockito.when(userMapper.toDto(eq(u), any())).thenReturn(dto);
@Test
void listSubscribedPosts() throws Exception {
User user = new User();
user.setUsername("bob");
com.openisle.model.Category cat = new com.openisle.model.Category();
cat.setName("tech");
com.openisle.model.Post post = new com.openisle.model.Post();
post.setId(6L);
post.setTitle("fav");
post.setCreatedAt(java.time.LocalDateTime.now());
post.setCategory(cat);
post.setAuthor(user);
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
Mockito.when(subscriptionService.getSubscribedPosts("bob")).thenReturn(java.util.List.of(post));
PostMetaDto meta = new PostMetaDto();
meta.setId(6L);
meta.setTitle("fav");
Mockito.when(userMapper.toMetaDto(post)).thenReturn(meta);
mockMvc
.perform(
get("/api/users/me").principal(new UsernamePasswordAuthenticationToken("alice", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.avatar").value("http://x/avatar.png"));
}
mockMvc.perform(get("/api/users/bob/subscribed-posts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("fav"));
}
@Test
void uploadAvatar() throws Exception {
MockMultipartFile file = new MockMultipartFile(
"file",
"a.png",
MediaType.IMAGE_PNG_VALUE,
"img".getBytes()
);
Mockito.when(imageUploader.upload(any(), eq("a.png"))).thenReturn(
java.util.concurrent.CompletableFuture.completedFuture("http://img/a.png")
);
@Test
void listUserReplies() throws Exception {
User user = new User();
user.setUsername("bob");
com.openisle.model.Post post = new com.openisle.model.Post();
post.setId(5L);
com.openisle.model.Category cat = new com.openisle.model.Category();
cat.setName("tech");
post.setCategory(cat);
com.openisle.model.Comment comment = new com.openisle.model.Comment();
comment.setId(4L);
comment.setContent("hi");
comment.setCreatedAt(java.time.LocalDateTime.now());
comment.setAuthor(user);
comment.setPost(post);
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
Mockito.when(commentService.getRecentCommentsByUser("bob", 50)).thenReturn(java.util.List.of(comment));
CommentInfoDto info = new CommentInfoDto();
info.setId(4L);
info.setContent("hi");
Mockito.when(userMapper.toCommentInfoDto(comment)).thenReturn(info);
mockMvc
.perform(
multipart("/api/users/me/avatar")
.file(file)
.principal(new UsernamePasswordAuthenticationToken("alice", "p"))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.url").value("http://img/a.png"));
mockMvc.perform(get("/api/users/bob/replies"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(4));
}
Mockito.verify(userService).updateAvatar("alice", "http://img/a.png");
}
@Test
void aggregateUserData() throws Exception {
User user = new User();
user.setId(2L);
user.setUsername("bob");
user.setEmail("b@e.com");
com.openisle.model.Category cat = new com.openisle.model.Category();
cat.setName("tech");
com.openisle.model.Post post = new com.openisle.model.Post();
post.setId(3L);
post.setTitle("hello");
post.setCreatedAt(java.time.LocalDateTime.now());
post.setCategory(cat);
post.setAuthor(user);
com.openisle.model.Comment comment = new com.openisle.model.Comment();
comment.setId(4L);
comment.setContent("hi");
comment.setCreatedAt(java.time.LocalDateTime.now());
comment.setAuthor(user);
comment.setPost(post);
@Test
void uploadAvatarRejectsNonImage() throws Exception {
MockMultipartFile file = new MockMultipartFile(
"file",
"a.txt",
MediaType.TEXT_PLAIN_VALUE,
"text".getBytes()
);
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
Mockito.when(postService.getRecentPostsByUser("bob", 10)).thenReturn(java.util.List.of(post));
Mockito.when(commentService.getRecentCommentsByUser("bob", 50)).thenReturn(java.util.List.of(comment));
UserDto dtoAgg = new UserDto();
dtoAgg.setId(2L);
dtoAgg.setUsername("bob");
Mockito.when(userMapper.toDto(eq(user), any())).thenReturn(dtoAgg);
PostMetaDto metaAgg = new PostMetaDto();
metaAgg.setId(3L);
metaAgg.setTitle("hello");
Mockito.when(userMapper.toMetaDto(post)).thenReturn(metaAgg);
CommentInfoDto infoAgg = new CommentInfoDto();
infoAgg.setId(4L);
infoAgg.setContent("hi");
Mockito.when(userMapper.toCommentInfoDto(comment)).thenReturn(infoAgg);
mockMvc
.perform(
multipart("/api/users/me/avatar")
.file(file)
.principal(new UsernamePasswordAuthenticationToken("alice", "p"))
)
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.error").value("File is not an image"));
mockMvc.perform(get("/api/users/bob/all"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.user.id").value(2))
.andExpect(jsonPath("$.posts[0].id").value(3))
.andExpect(jsonPath("$.replies[0].id").value(4));
}
Mockito.verify(imageUploader, Mockito.never()).upload(any(), any());
}
@Test
void getUserByName() throws Exception {
User u = new User();
u.setId(2L);
u.setUsername("bob");
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(u));
UserDto dto = new UserDto();
dto.setId(2L);
dto.setUsername("bob");
Mockito.when(userMapper.toDto(eq(u), any())).thenReturn(dto);
mockMvc
.perform(get("/api/users/bob"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(2));
}
@Test
void listUserPosts() throws Exception {
User user = new User();
user.setUsername("bob");
com.openisle.model.Category cat = new com.openisle.model.Category();
cat.setName("tech");
com.openisle.model.Post post = new com.openisle.model.Post();
post.setId(3L);
post.setTitle("hello");
post.setCreatedAt(java.time.LocalDateTime.now());
post.setCategory(cat);
post.setAuthor(user);
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
Mockito.when(postService.getRecentPostsByUser("bob", 10)).thenReturn(java.util.List.of(post));
PostMetaDto meta = new PostMetaDto();
meta.setId(3L);
meta.setTitle("hello");
Mockito.when(userMapper.toMetaDto(post)).thenReturn(meta);
mockMvc
.perform(get("/api/users/bob/posts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("hello"));
}
@Test
void listSubscribedPosts() throws Exception {
User user = new User();
user.setUsername("bob");
com.openisle.model.Category cat = new com.openisle.model.Category();
cat.setName("tech");
com.openisle.model.Post post = new com.openisle.model.Post();
post.setId(6L);
post.setTitle("fav");
post.setCreatedAt(java.time.LocalDateTime.now());
post.setCategory(cat);
post.setAuthor(user);
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
Mockito.when(subscriptionService.getSubscribedPosts("bob")).thenReturn(java.util.List.of(post));
PostMetaDto meta = new PostMetaDto();
meta.setId(6L);
meta.setTitle("fav");
Mockito.when(userMapper.toMetaDto(post)).thenReturn(meta);
mockMvc
.perform(get("/api/users/bob/subscribed-posts"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("fav"));
}
@Test
void listUserReplies() throws Exception {
User user = new User();
user.setUsername("bob");
com.openisle.model.Post post = new com.openisle.model.Post();
post.setId(5L);
com.openisle.model.Category cat = new com.openisle.model.Category();
cat.setName("tech");
post.setCategory(cat);
com.openisle.model.Comment comment = new com.openisle.model.Comment();
comment.setId(4L);
comment.setContent("hi");
comment.setCreatedAt(java.time.LocalDateTime.now());
comment.setAuthor(user);
comment.setPost(post);
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
Mockito.when(commentService.getRecentCommentsByUser("bob", 50)).thenReturn(
java.util.List.of(comment)
);
CommentInfoDto info = new CommentInfoDto();
info.setId(4L);
info.setContent("hi");
Mockito.when(userMapper.toCommentInfoDto(comment)).thenReturn(info);
mockMvc
.perform(get("/api/users/bob/replies"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(4));
}
@Test
void aggregateUserData() throws Exception {
User user = new User();
user.setId(2L);
user.setUsername("bob");
user.setEmail("b@e.com");
com.openisle.model.Category cat = new com.openisle.model.Category();
cat.setName("tech");
com.openisle.model.Post post = new com.openisle.model.Post();
post.setId(3L);
post.setTitle("hello");
post.setCreatedAt(java.time.LocalDateTime.now());
post.setCategory(cat);
post.setAuthor(user);
com.openisle.model.Comment comment = new com.openisle.model.Comment();
comment.setId(4L);
comment.setContent("hi");
comment.setCreatedAt(java.time.LocalDateTime.now());
comment.setAuthor(user);
comment.setPost(post);
Mockito.when(userService.findByIdentifier("bob")).thenReturn(Optional.of(user));
Mockito.when(postService.getRecentPostsByUser("bob", 10)).thenReturn(java.util.List.of(post));
Mockito.when(commentService.getRecentCommentsByUser("bob", 50)).thenReturn(
java.util.List.of(comment)
);
UserDto dtoAgg = new UserDto();
dtoAgg.setId(2L);
dtoAgg.setUsername("bob");
Mockito.when(userMapper.toDto(eq(user), any())).thenReturn(dtoAgg);
PostMetaDto metaAgg = new PostMetaDto();
metaAgg.setId(3L);
metaAgg.setTitle("hello");
Mockito.when(userMapper.toMetaDto(post)).thenReturn(metaAgg);
CommentInfoDto infoAgg = new CommentInfoDto();
infoAgg.setId(4L);
infoAgg.setContent("hi");
Mockito.when(userMapper.toCommentInfoDto(comment)).thenReturn(infoAgg);
mockMvc
.perform(get("/api/users/bob/all"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.user.id").value(2))
.andExpect(jsonPath("$.posts[0].id").value(3))
.andExpect(jsonPath("$.replies[0].id").value(4));
}
}