Java 如何使用视图和路径变量测试Spring控制器?
如何在CreditGroup中传递Java 如何使用视图和路径变量测试Spring控制器?,java,spring,spring-mvc,junit,mockito,Java,Spring,Spring Mvc,Junit,Mockito,如何在CreditGroup中传递?还是有别的办法 控制器: @Controller @RequestMapping("/ingredients/groups") @RequiredArgsConstructor @PermissionUserWrite public class IngredientGroupController { private static final String VIEWS_PATH = "/pages/ingredient/gr
?还是有别的办法
控制器:
@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";
}
}
测试:
我不知道IngredientGroup
中的字段是什么。但是,我假设有name
和something
字段
将对象用作@PathVariable
时,需要将其属性作为查询参数传递。因此,在您的情况下,您将要测试的url如下所示:
http://localhost:8080/ingredients/groups/1?name=xxxxxx&something=otherthing
InCreditGroup
应该是什么?对于@PathVariable
(例如long),您通常会使用基本数据类型,而不是复杂的数据类型。看一看它是实体,您是否在内存中的数据库中加载了id=1的IngredientGroup
,以便进行测试?我想通过使用mockito来避免这种情况。但这似乎是Spring尝试使用@PathVariable(“id”)
调用方法findById
(JpaRepository)的唯一方法。它返回null(控制器返回状态404),因为我没有用于测试的DB。我想通过使用mockito来避免这种情况。如果您的问题得到了回答,请标记此问题已解决,并在另一个问题中添加mocking存储库。检查这个
@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"));
}
}
@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());
}