【问题标题】:Testing controllers with Authentication class in spring在 Spring 中使用 Authentication 类测试控制器
【发布时间】:2019-10-10 13:29:31
【问题描述】:

在我的控制器方法中,我使用身份验证类来获取登录的用户数据。

看起来像这样:

@GetMapping("/somepath")
    public ResponseEntity<SomeType> someMethod(Authentication user){
        ...
    }

我不知道如何测试它。我尝试了@WithMockUser 注释,.with(user(...)),但它不起作用。有谁知道如何正确地做到这一点?

【问题讨论】:

  • 它不起作用。结果是什么。 Authentication 是 null 还是别的什么?

标签: java spring spring-boot spring-security spring-test


【解决方案1】:

理想情况下,如果您遵循良好的编码实践,您将永远不会为控制器或数据律师编写测试用例。 理想情况下,测试用例用于测试代码中涉及的一些业务逻辑,通过引用我们应该将所有业务写入服务。

像请求验证这样的控制器应该做的工作要少得多。

下面的代码可能会帮助您测试控制器方法。

   MockMvc mvc;
   @Autowired
   WebApplicationContext webApplicationContext;

   protected void setUp() {
      mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
   }
   protected String mapToJson(Object obj) throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(obj);
   }
   protected <T> T mapFromJson(String json, Class<T> clazz)
      throws JsonParseException, JsonMappingException, IOException {

      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(json, clazz);
   }


@Test
public void someMethodTest() throws Exception {
   String uri = "/somepath";
   Authentication authentication = new Authentication ();

   String inputJson = super.mapToJson(authentication);
   MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri)
      .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn();

   int status = mvcResult.getResponse().getStatus();
   assertEquals(200, status);
   String content = mvcResult.getResponse().getContentAsString();
   // Assert whatever you want 
   assertEquals();
}

【讨论】:

    猜你喜欢
    • 2020-12-04
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 2021-02-08
    • 1970-01-01
    • 2019-03-28
    相关资源
    最近更新 更多