Spring 启动测试 - 使用@WithMockUser 发布的内容为空
Spring Boot tests - posted content is null with @WithMockUser
我正在尝试使用 @WithMockUser 测试来测试我的 CommentController,但它似乎找不到用户(因为用户 ID (author_id) 为空)或评论的内容。我不确定测试是否以正确的方式完成(我仍然是初学者),但我试图实现的是尽可能高的代码覆盖率,但我之前的测试不包括搜索经过身份验证的用户和创建评论:
mockMvc.perform(get("/post/3/comment").with(authentication(authentication)).content("content")).andExpect(status().is3xxRedirection()).andExpect(view().name("redirect:/post/{id}/"));
package com.paulthemenace.blog.controllers;
import com.paulthemenace.blog.models.Comment;
import com.paulthemenace.blog.models.User;
import com.paulthemenace.blog.repositories.UserRepository;
import com.paulthemenace.blog.services.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import
org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class CommentController {
@Autowired
private UserRepository userRepo;
@Autowired
private CommentService comSrv;
@RequestMapping(value = "/post/{id}/comment")
public String comment(@PathVariable("id") Long id,
@ModelAttribute("comment") Comment comment, Model model) throws
Exception {
Authentication auth =
SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
String name = auth.getName();
User currentUser = userRepo.findByUsername(name);
if (comment.getContent() != "") {
comment.setAuthor(currentUser);
comSrv.create(comment);
}
}
return "redirect:/post/{id}/";
}
}
评论控制器测试
import com.paulthemenace.blog.controllers.CommentController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import
org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
@SpringBootTest
@RunWith(SpringRunner.class)
@WebAppConfiguration
public class CommentControllerTest {
@Autowired
private CommentController commentController;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(commentController).build();
}
@Test
public void controllerIsNotNull() {
assertThat(commentController).isNotNull();
}
@Test
@WithMockUser(username = "user", password = "user")
public void checkIfContainsAuthenticatedUserAndCreatesComment()
throws Exception {
mockMvc.perform(post("/post/3/comment")
.content("comment
content")).andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/post/{id}/"));
}
}
堆栈跟踪
测试是否正确?我希望这个项目在测试驱动开发中进行,但我失败得很惨。
我在 Spring Boot 中搜索了有关测试的资源,但其中 none 帮助我解决了这个问题..
感谢您的帮助!
感谢 Barath 发送的 link,我设法修复它并在该控制器上获得 100% 的代码覆盖率:
@Test
@WithMockUser(username = "sure", password = "sure")
public void checkIfContainsAuthenticatedUserAndCreatesComment() throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post("/post/3/comment");
Comment com = new Comment();
String name = auth.getName();
User currentUser = userRepo.findByUsername(name);
com.setAuthor(currentUser);
com.setContent("ahdsf");
request.flashAttr("comment", com);
mockMvc.perform(request).andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/post/{id}/"));
}
我真蠢,我没注意到它还在读取 MYSQL 的用户,所以我不得不插入 table 的 'real' 用户。
再次感谢!
我正在尝试使用 @WithMockUser 测试来测试我的 CommentController,但它似乎找不到用户(因为用户 ID (author_id) 为空)或评论的内容。我不确定测试是否以正确的方式完成(我仍然是初学者),但我试图实现的是尽可能高的代码覆盖率,但我之前的测试不包括搜索经过身份验证的用户和创建评论:
mockMvc.perform(get("/post/3/comment").with(authentication(authentication)).content("content")).andExpect(status().is3xxRedirection()).andExpect(view().name("redirect:/post/{id}/"));
package com.paulthemenace.blog.controllers;
import com.paulthemenace.blog.models.Comment;
import com.paulthemenace.blog.models.User;
import com.paulthemenace.blog.repositories.UserRepository;
import com.paulthemenace.blog.services.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import
org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class CommentController {
@Autowired
private UserRepository userRepo;
@Autowired
private CommentService comSrv;
@RequestMapping(value = "/post/{id}/comment")
public String comment(@PathVariable("id") Long id,
@ModelAttribute("comment") Comment comment, Model model) throws
Exception {
Authentication auth =
SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
String name = auth.getName();
User currentUser = userRepo.findByUsername(name);
if (comment.getContent() != "") {
comment.setAuthor(currentUser);
comSrv.create(comment);
}
}
return "redirect:/post/{id}/";
}
}
评论控制器测试
import com.paulthemenace.blog.controllers.CommentController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import
org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
@SpringBootTest
@RunWith(SpringRunner.class)
@WebAppConfiguration
public class CommentControllerTest {
@Autowired
private CommentController commentController;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(commentController).build();
}
@Test
public void controllerIsNotNull() {
assertThat(commentController).isNotNull();
}
@Test
@WithMockUser(username = "user", password = "user")
public void checkIfContainsAuthenticatedUserAndCreatesComment()
throws Exception {
mockMvc.perform(post("/post/3/comment")
.content("comment
content")).andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/post/{id}/"));
}
}
堆栈跟踪
测试是否正确?我希望这个项目在测试驱动开发中进行,但我失败得很惨。 我在 Spring Boot 中搜索了有关测试的资源,但其中 none 帮助我解决了这个问题..
感谢您的帮助!
感谢 Barath 发送的 link,我设法修复它并在该控制器上获得 100% 的代码覆盖率:
@Test
@WithMockUser(username = "sure", password = "sure")
public void checkIfContainsAuthenticatedUserAndCreatesComment() throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post("/post/3/comment");
Comment com = new Comment();
String name = auth.getName();
User currentUser = userRepo.findByUsername(name);
com.setAuthor(currentUser);
com.setContent("ahdsf");
request.flashAttr("comment", com);
mockMvc.perform(request).andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/post/{id}/"));
}
我真蠢,我没注意到它还在读取 MYSQL 的用户,所以我不得不插入 table 的 'real' 用户。 再次感谢!