【发布时间】:2020-10-23 15:21:26
【问题描述】:
如何传递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应该是什么?您通常会为@PathVariable使用原始数据类型(例如 long),而不是复杂数据类型。看看docs.spring.io/spring-framework/docs/current/… -
您是否在为测试设置的内存数据库中加载了任何 id=1 的
IngredientGroup? -
我想通过使用 mockito 来避免这种情况。但看起来这是唯一的方法
标签: java spring spring-mvc junit mockito