gpt4 book ai didi

java - 使用名称模拟身份验证

转载 作者:行者123 更新时间:2023-11-29 08:33:20 25 4
gpt4 key购买 nike

我正在测试我的 Spring MVC 应用程序。 要求 是模拟 SecurityContext,但我需要使用某个名称的 Authentication,而不是 null。有什么办法吗?

这是我的代码:

Authentication auth = Mockito.mock(Authentication.class);
SecurityContext secCont = Mockito.mock(SecurityContext.class);
Mockito.when(secCont.getAuthentication()).thenReturn(auth);
SecurityContextHolder.setContext(secCont);

最佳答案

你在这里模拟了 Spring 的 Authentication 对象:

Authentication auth = Mockito.mock(Authentication.class);

并且您已告知 Spring 的 SecurityContextHolder 将此 Authentication 对象存储在此处:

Mockito.when(secCont.getAuthentication()).thenReturn(auth);

因此,如果您希望模拟的 Authentication 对象返回“某个名称”,则只需在 上设置一些模拟期望。例如:

Mockito.when(auth.getName()).thenReturn("aName");

关于java - 使用名称模拟身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46037890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com