我有一个 Spring Boot 应用程序,它需要登录才能执行某些操作。我正在尝试使用 测试它们MockMvc
,但它似乎不起作用。我不断收到状态为 403(禁止)的 HTTP 响应。身份验证部分可能有问题。
我已尝试按照文档进行操作,但无法使其正常工作。
这是我当前的测试代码:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@WebIntegrationTest("server.port = 8093")
public class PasswordChangeTests {
@Autowired
private EmbeddedWebApplicationContext webApplicationContext;
@Autowired
private UserRepository userRepository;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
this.mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.build();
}
@Test
public void changePasswordWorks() throws Exception {
// Send password change request
PasswordChangeRepresentation passwordChange = new PasswordChangeRepresentation(DefaultUsers.Admin.getPassword(), "12345678");
mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.POST, "/password/change")
.content(new ObjectMapper().writeValueAsString(passwordChange))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
// Check that the password has been changed
User user = this.userRepository.findByUsername(DefaultUsers.Admin.getEmail());
Assert.assertEquals(user.getPassword(), "12345678");
}
}
抱歉,如果我遗漏了一些明显的东西。这是我第一次体验spring boot。