【发布时间】:2016-08-03 19:08:00
【问题描述】:
我在其他任何地方都找不到这个问题。
我的单元测试设置如下:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
//@DatabaseSetup("classpath:decks.xml")
@WebIntegrationTest
public class DeckControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
@WithMockUser
public void addDeck_ShouldRedirectIfUserLoggedInAndPostsInvalidDeck() throws Exception {
DeckbuilderForm form = new DeckbuilderForm();
ObjectMapper mapper = new ObjectMapper();
String queryString = mapper.convertValue(form, UriFormat.class).toString();
mockMvc.perform(post("/decks")
.with(csrf())
.contentType(MediaType.ALL)
.content(queryString)
)
.andExpect(status().is3xxRedirection())
.andExpect(flash().attributeExists("flash"));
}
@Test
@WithMockUser
public void addDeck_ShouldBeOkWithValidInput() throws Exception {
DeckbuilderForm form = sampleValidDeckbuilderForm();
ObjectMapper mapper = new ObjectMapper();
String queryString = mapper.convertValue(form, UriFormat.class).toString();
mockMvc.perform(post("/decks")
.with(csrf().useInvalidToken())
.content(queryString)
)
.andExpect(status().is3xxRedirection());
}
}
我在运行测试时收到以下堆栈跟踪:
java.lang.IllegalArgumentException:HttpServletRequest 属性 必须包含属性的 HttpServletResponse javax.servlet.http.HttpServletResponse
这来自 LazyCsrfTokenRepository 类:
private HttpServletResponse getResponse(HttpServletRequest request) {
HttpServletResponse response = (HttpServletResponse) request
.getAttribute(HTTP_RESPONSE_ATTR);
if (response == null) {
throw new IllegalArgumentException(
"The HttpServletRequest attribute must contain an HttpServletResponse for the attribute "
+ HTTP_RESPONSE_ATTR);
}
return response;
}
任何解决此问题的建议将不胜感激,我知道通常人们会使用 @ContextConfiguration 而不是 @SpringApplicationConfiguration 但我只能使用这种方法,因为我使用的是 Java Config 并且不想复制我的配置用于测试。
【问题讨论】:
标签: spring spring-mvc junit spring-security mocking