简体   繁体   English

我正在学习如何为控制器进行单元测试,但我不知道如何正确地进行

[英]I am learning how to do the unit tests for the controllers and i don't know how to do it correctly

I'm learning how to test controllers and I still don't understand some things.我正在学习如何测试控制器,但我仍然不明白一些事情。 I've watched some tutorials and I read some pages to learn but I don't understand 100%.我看过一些教程,也阅读了一些页面来学习,但我没有 100% 理解。 I tried to do it but I don't think it's correct.我试图这样做,但我认为它不正确。 I'm using Spring Boot and Mock.我正在使用 Spring 引导和模拟。

This is my controller class:这是我的 controller class:

@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";
}

This is my test class:这是我的测试 class:

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

I tried doing it seeing previous methods some people made and with what I read before in notes I took, but i don't really understand so if you could tell me if that's correct or what is wrong and I could do better and I'd appreciate it.我试着看一些人以前的方法,以及我之前在笔记中读到的内容,但我不太明白,所以如果你能告诉我这是正确的还是错误的,我可以做得更好,我会欣赏它。 Thank you so much!太感谢了!

First of all, you're trying to mock a @GetMapping as a post() and it will not work.首先,您试图将@GetMapping模拟为post()并且它不起作用。

Second, it seems that your resource does not need any parameter as it only gathers information about the user that is logged in your system, am I correct?其次,您的资源似乎不需要任何参数,因为它只收集有关登录您系统的用户的信息,对吗?

So, your test should look like:因此,您的测试应如下所示:

@WithMockUser(value = "spring")
@Test
void testProcessCreationUser() throws Exception{
    mockMvc.perform(get("/userProfile")
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.view().name("users/createClienteForm"));
    
}

You should review to which page your user will be redirected at the end, as users/createClienteForm doesn't seem to be the corrected one in your mock.您应该查看您的用户最终将被重定向到哪个页面,因为users/createClienteForm在您的模拟中似乎不是正确的页面。

Also, always choose a name for your test that correctly explains what your test is doing/verifying.此外,请始终为您的测试选择一个正确解释您的测试正在做什么/验证的名称。 I think testShowUserProfile should be fine in your case.我认为testShowUserProfile在你的情况下应该没问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我是一个初学者程序员,我不知道 Java 中的参数是如何工作的。 那么它们是如何工作的呢? - I am a beginner programmer and I don't know how parameters work in Java. So how do they work? 我不知道如何做一个数组来存储每个学期的详细信息。 我应该创建 class Student 的子类 - I don't know how to do an array to store for each semester the details. I am supposed to create a subclass of the class Student 如何修复这些单元测试? - How do I fix these Unit Tests? 如果我不知道我将传入多少参数,如何使用预准备语句? - How do I use a prepared statement if I don't know how many parameters I'll be passing in? 我正在学习如何开发应用程序,但我不知道为什么我的应用程序崩溃了 - I'm learning how to develop an app and I don't know why my app is crashed 如果我在编译时不知道该类,如何获取Enum的值? - How do I get the value of an Enum, if I don't know the class at compile time? 如何为参数化方法提供参数,该参数类型直到运行时才知道? - How do I supply an argument to a parameterized method, whose type I don't know until runtime? 我正在尝试获得组合,但我不知道该怎么做 - I'm trying to get combinations but I don't know how to do it 如何获得我不知道的数组的索引? - How do I get the index of an array which I don't know? 如果我不知道变量是正/负,如何在不调用函数或不使用if的情况下使其变为正数? - If I don't know if a variable is positive/negative, how do I make it positive without calling a function or using if?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM