java - 如何使用视图和路径变量测试 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"));
}
}
解决方案
我不知道这些领域是什么IngredientGroup
。但是,我认为有字段name
和something
.
当使用对象 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());
}
推荐阅读
- search - NetSuite 销售团队搜索
- visual-studio-code - 将 VSCode 调试图标提取到 PNG 文件
- regex - 如何使用 sed/perl/awk 查找和替换模式字符串?
- excel - 如何更正 Excel VBA 中的不正确乘法(自动向下舍入/丢失小数)?
- logic - 根据特定逻辑在 Tableau 中计算日期
- python - 如何使用 python 中的 def 函数和条件语句打印 2 个连续的红色或绿色蜡烛
- python - SQLDF 提取值并将其保存到文本文件
- python - 关于几个开发 Python 包的开发人员的问题
- android - 如何在 Jetpack Compose 中创建垂直无限轮播?
- javascript - 需要更改嵌入字体样式的大小