简体   繁体   English

使用MockMVC模拟SpringContextHolder

[英]Mock SpringContextHolder using MockMVC

I am writing unit test cases for Controller layer. 我正在为控制器层编写单元测试用例。 I have a call where i am getting user from Spring SecurityContextHolder. 我有一个电话,我从Spring SecurityContextHolder获取用户。 When i run my test case i get Null pointer exception because I don't know how to mock Spring security context. 当我运行测试用例时,我会得到Null指针异常,因为我不知道如何模拟Spring安全上下文。

Below is my code, any suggestion how to do it? 下面是我的代码,有什么建议怎么做?

Controller Methhod: 控制器方法:

@RequestMapping(method = RequestMethod.POST)
public void saveSettings(@RequestBody EmailSettingDTO emailSetting) {
    User user = ((CurrentUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser();
    settings.saveUserEmailSetting(user, emailSetting);

}

My Test case : 我的测试用例:

@Test  public void testSaveSettings() throws Exception {
mockMvc.perform(post(BASE_URL).content(this.objectMapper.writeValueAsString(emailDto))
  .contentType(MediaTypes.HAL_JSON)).andExpect(status().isOk());

} }

There is a Spring Security Test library for this purpose. 有一个用于此目的的Spring Security Test库。

You can use @WithMockUser to achieve this. 您可以使用@WithMockUser实现此目的。 See the post 帖子

You can use @WithUserDetails 您可以使用@WithUserDetails

this annotation can be added to a test method to emulate running with a UserDetails returned from the UserDetailsService. 可以将此注释添加到测试方法中,以模拟从UserDetailsS​​ervice返回的UserDetails运行。

By using this, you create a context to run a test in, for example: 通过使用此方法,您可以创建一个上下文来运行测试,例如:

@Test
@WithUserDetails("admin")
public void testAdmin() throws Exception {
    mockMvc.perform(...);
}

This will execute testAdmin() with the SecurityContext of admin. 这将使用admin的SecurityContext执行testAdmin()

But please note, in order to use this; 但是请注意,为了使用它; there must be a User persisted with the name admin , otherwise you will get result exceptions. 必须有一个名为adminUser ,否则您将获得结果异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM