我正在学习如何测试控制器,但我仍然不懂一些东西。我看了一些教程,我读了一些页来学习,但我不理解100%。我试着这么做,但我觉得不对。我用的是Spring Boot和仿制品。
这是我的控制器类:
@Autowired
private UserDetailsServiceImpl userService;
@Autowired
private ShopService shopService;
@Autowired
private GameService gameService;
@GetMapping(value = "/userProfile")
public String userProfile(final Model model, final HttpServletRequest request) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object principal = auth.getPrincipal();
User us = null;
if (principal instanceof User) {
us = (User) principal;
}
model.addAttribute("user", us);
model.addAttribute("teamsCreated", this.userService.teamsCreated(us));
model.addAttribute("teamshejoined", this.userService.teamsHeJoined(us));
model.addAttribute("gamesheplays", this.gameService.findGamesHePlays(us.getId()));
model.addAttribute("groupgamesheplays", this.gameService.findGroupHePlays(us));
model.addAttribute("prizehewon", this.gameService.getPrizeHeWon(us));
return "user/profile";
}
这是我的测试课:
@Autowired
private MockMvc mockMvc;
@MockBean
private UserDetailsServiceImpl userService;
@MockBean
private ShopService shopService;
@MockBean
private UserRepository userRepository;
@MockBean
private DataUserRepository dataUserRepository;
private User user;
private DataUser dataUser;
private Team team;
private Set<User> people;
@BeforeEach
void setUp() {
user = new User();
user.setId(12L);
user.setUsername("usertest");
user.setPassword("Pass1234");
dataUser.setId(915495L);
dataUser.setMoney(1);
dataUser.setUser(user);
user.setDataUser(dataUser);
people = new HashSet<>();
people.add(user);
team = new Team();
team.setId(2L);
team.setName("team1");
team.setCreator(user);
team.setPeople(people);
team.setCreationDate(Date.from(Instant.now()));
}
@WithMockUser(value = "spring")
@Test
void testProcessCreationUser() throws Exception{
mockMvc.perform(post("/userProfile")
.with(csrf())
.param("username", "usertest")
.param("password", "Pass1234")
.param("id", "49L")
.param("dataUser", ?????? )) // the ?? is because I dont know how to add a dataUser type, I only know Strings
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.view().name("users/createClienteForm"));
}
我试着看一些人以前做的方法和我以前在笔记上读到的东西,但我不太明白,所以如果你能告诉我这是正确的还是错误的,我可以做得更好,我会很感激。非常感谢!
1条答案
按热度按时间sqougxex1#
首先,你是在嘲笑
@GetMapping
作为一个post()
但这是行不通的。其次,您的资源似乎不需要任何参数,因为它只收集有关登录到您的系统中的用户的信息,对吗?
所以,你的测试应该是这样的:
您应该在最后查看您的用户将被重定向到哪个页面,如下所示:
users/createClienteForm
似乎不是你模仿的正确答案。此外,请始终为测试选择一个名称,该名称正确地解释了测试正在执行/验证的操作。我想
testShowUserProfile
对你来说应该没问题。