首页 > 解决方案 > 如何使用视图和路径变量测试 Spring 控制器?

问题描述

如何通过一个ingredientGroup?还是有其他方法?

控制器:

@Controller
@RequestMapping("/ingredients/groups")
@RequiredArgsConstructor
@PermissionUserWrite
public class IngredientGroupController {
    private static final String VIEWS_PATH = "/pages/ingredient/group/";
    private final IngredientGroupService ingredientGroupService;

    @GetMapping("{id}")
    public String show(@PathVariable("id") IngredientGroup group, Model model) {
        if (group == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Ingredient group not found");
        }

        model.addAttribute("group", group);
        return VIEWS_PATH + "show";
    }
}

测试:

@SpringBootTest
@AutoConfigureMockMvc
class IngredientGroupControllerTest {
    private static final String VIEWS_PATH = "/pages/ingredient/group/";
    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithMockAdmin
    void show_for_admin() throws Exception {
        var ingredientGroup = Mockito.mock(IngredientGroup.class);
        mockMvc.perform(MockMvcRequestBuilders.get("/ingredients/groups/{id}", 1))
                .andExpect(status().isOk())
                .andExpect(view().name(VIEWS_PATH+"show"));
    }
}

标签: javaspringspring-mvcjunitmockito

解决方案


我不知道这些领域是什么IngredientGroup。但是,我认为有字段namesomething.

当使用对象 as@PathVariable时,您应该将其属性作为查询参数传递。因此,在您的情况下,您要测试的网址如下所示: http://localhost:8080/ingredients/groups/1?name=xxxxxx&something=otherthing

@Test
public void show_for_admin() throws Exception {
    var ingredientGroup = Mockito.mock(IngredientGroup.class);
     mockMvc.perform(MockMvcRequestBuilders.get(String.format("/ingredients/groups/%d", 1), 
                                            ingredientGroup.getName(), 
                                            ingredientGroup.getSomething()))
                .andExpect(status().isOk());
}

推荐阅读