【发布时间】:2019-11-02 17:00:22
【问题描述】:
成功认证后,我将认证用户保存在会话中。 之后,我使用 @SessionAttributes("user")
在任何控制器中检索用户现在我正在尝试测试它:
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = SpringSecurityTestConfig.class
)
public class ProfileMetaDataControllerTest {
private MockMvc mockMvc;
@Autowired
private MyController myController;
@Autowired
private WebApplicationContext context;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(myController).build();
}
@Test
@WithUserDetails("userMail@hotmail.com")
public void shouldReturnDefaultMessage() throws Exception {
String expectedValue ="greeting";
MvcResult result = this.mockMvc.perform(get("/contentUrl")
.contentType(MediaType.TEXT_PLAIN)
.content("romakapt@gmx.de"))
.andDo(print())
.andExpect(content().string(expectedValue))
.andReturn();
}
}
还有我的控制器,它将被测试:
@RestController
@RequestMapping("/profile")
@SessionAttributes("user")
public class ProfileMetaDataController {
@GetMapping("/contentUrl")
@ResponseBody
public List<String> getInformation(Model model) throws IOException {
User user = Optional.ofNullable((User) model.asMap().get("user")); //User ist null!!!!
}
}
用户为空,因为我的 AuthenticationSuccessHandler 从不调用 onAuthenticationSuccess 方法,我将用户存储在会话中。
我该如何处理? 通常 UsernamePasswordAuthenticationFilter 会调用我的 AuthenticationSuccessHandler,但不会在 MockMVC 测试期间调用。
【问题讨论】:
标签: spring-boot spring-security spring-test-mvc