gpt4 book ai didi

java - Spring Boot 测试 - @WithMockUser 发布的内容为空

转载 作者:行者123 更新时间:2023-12-02 12:13:02 30 4
gpt4 key购买 nike

我正在尝试使用 @WithMockUser 测试来测试我的 CommentController,但似乎找不到用户(因为用户 id (author_id) 为空)或评论内容。我不确定测试是否以正确的方式完成(我仍然是初学者),但我试图实现的是尽可能高的代码覆盖率,但我之前的测试不包括经过身份验证的用户的搜索和创建评论:

mockMvc.perform(get("/post/3/comment").with(authentication(authentication)).content("content")).andExpect(status().is3xxRedirection()).andExpect (view().name("重定向:/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}/";
}

}

评论 Controller 测试

    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}/"));


}


}

堆栈跟踪

https://pastebin.com/2SSKRjwd

测试正确吗?我希望这个项目是在测试驱动开发中进行的,但我失败得很惨。 我在 Google 上搜索了有关 Spring Boot 测试的资源,但没有一个能帮助我解决这个问题。

感谢您的帮助!

最佳答案

感谢 Barath 发送的链接,我成功修复了该问题并在该 Controller 上获得了 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 读取用户,所以我必须从表中插入一个“真实”用户。再次感谢!

关于java - Spring Boot 测试 - @WithMockUser 发布的内容为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46388501/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com