这是这个问题的延续Spring WebMvcTest如何模拟身份验证?
我正在尝试在 Spring-boot 中测试接收一个控制器方法Authentication
对象作为参数。控制器是一个RestController
with @CrossOrigin
注解。该方法如下所示:
@GetMapping("/authentication")
public String testAuthentication(Authentication authentication) {
UserDetailsStub userDetailsStub = (UserDetailsStub) authentication.getPrincipal();
return userDetailsStub.getUsername();
}
正如您所看到的,我从参数中的身份验证中获取了主体。
问题是,在我的WebMvcTest
测试用例我得到一个NullPointerException
因为在测试用例中,authentication
似乎为空。我的问题是为什么?
我尝试过添加一个given
调用将返回一个自定义的UserDetails
对象在一个@PostConstruct
测试用例中带注释的方法,但我仍然得到NullPointerException
.
我的测试用例如下所示:
@Import(SecurityConfiguration.class)
@RunWith(SpringRunner.class)
@WebMvcTest(PDPController.class)
@AutoConfigureMockMvc(addFilters = false)
public class PDPControllerTests {
@Autowired
private MockMvc mvc;
@MockBean(name = "userDetailsService")
private MyUserDetailsService userDetailsService;
//..
@PostConstruct
public void setup() {
given(userDetailsService.loadUserByUsername(anyString()))
.willReturn(new UserDetailsStub());
}
//..
@Test
@WithUserDetails(value = "username", userDetailsServiceBeanName = "userDetailsService")
public void testAuthentication() throws Exception {
mvc.perform(get("/pdps/authentication").secure(true)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
Why is authentication
测试用例中为 null,即使我在@PostConstruct
method?
可以在此处找到具有重现错误的最少代码的 GitHub 项目。https://github.com/Kars1090/SpringSecurityTest
Thanks!