【发布时间】:2019-08-17 07:39:20
【问题描述】:
我正在使用 Spring Boot 2.0.8.RELEASE。我有一个控制器,它具有以下方法构造
@PostMapping(value = "/profile/change-password", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public Mono<String> changePasswordSubmit(Authentication authentication, @RequestBody MultiValueMap<String, String> formData) {
我的单元测试看起来像:
@RunWith(SpringRunner.class)
@WebFluxTest(controllers = ChangePasswordController.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Import({ThymeleafAutoConfiguration.class, SpringSecurityContextUtils.class})
@WithMockUser(username = "test", password = "password")
public class ChangePasswordControllerTest {
@Autowired
WebTestClient webTestClient;
@MockBean
SpringUserDetailsRepository userDetailsRepository;
@Autowired
ChangePasswordController controller;
@MockBean
Authentication authentication;
@Test
public void addNewEntrySubmit() {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
formData.put("password1", Collections.singletonList("password"));
formData.put("password2", Collections.singletonList("password"));
webTestClient.post().uri("/profile/change-password").contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(formData)).exchange().expectStatus().isSeeOther().expectHeader().valueEquals(HttpHeaders.LOCATION, "/page/1");
// verify(userDetailsRepository).updatePassword(captor.capture(), captor.capture());
doNothing().when(userDetailsRepository).updatePassword(any(), any());
}
}
我的问题是,当我运行测试时,控制器上的 Authentication 值为 null。我已尝试添加安全上下文,但在正确处理时遇到了问题。我该如何解决这个问题
更新: 链接到示例存储库:https://github.com/dmbeer/thymeleaf-spring-security-test
【问题讨论】:
-
似乎还有其他事情发生。当我将您的测试和控制器复制到我的应用程序中时,测试完成得很好。我不得不对其进行调整以删除您的一些内部结构并添加一个 csrf 令牌,但您可以在 github.com/jzheaux/so-55365324 看到我的示例应用程序。
-
嗨@jzheaux,谢谢你,似乎如果我将你的Spring Boot版本更改为2.0.8.RELEASE,它会失败并出现同样的错误。我已经更新了 Spring Boot 版本的问题。
标签: spring-boot spring-security spring-webflux spring-test