【问题标题】:How to test Spring controllers with a view and path variable?如何使用视图和路径变量测试 Spring 控制器?
【发布时间】: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/…
  • 实体spring data
  • 您是否在为测试设置的内存数据库中加载了任何 id=1 的 IngredientGroup
  • 我想通过使用 mockito 来避免这种情况。但看起来这是唯一的方法

标签: java spring spring-mvc junit mockito


【解决方案1】:

我不知道IngredientGroup 中的字段是什么。但是,我认为有字段namesomething

将对象用作@PathVariable 时,您应该将其属性作为查询参数传递。因此,在您的情况下,您要测试的 url 如下所示: 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());
}

【讨论】:

  • Spring 尝试使用@PathVariable("id") 调用方法findById (JpaRepository)。它返回 null(并且控制器返回状态 404),因为我没有用于测试的数据库。我想通过使用 mockito 来避免这种情况
  • 如果您的问题得到解答,请将其标记为已解决并在另一个问题中添加模拟存储库。检查这个stackoverflow.com/questions/51247796/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-05
  • 2018-01-31
  • 2014-08-23
  • 1970-01-01
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多