@Test // SPR-13079 public void deferredResultWithDelayedError() throws Exception { MvcResult mvcResult = this.mockMvc.perform(get("/1").param("deferredResultWithDelayedError", "true")) .andExpect(request().asyncStarted()) .andReturn(); this.mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().is5xxServerError()) .andExpect(content().string("Delayed Error")); }
private MvcResult getMvcResult(ResultActions perform, boolean isAsyncRequest) throws Exception { MvcResult mvcResult; if (isAsyncRequest) { MvcResult startedAsyncRequestProcessing = perform.andExpect(MockMvcResultMatchers.request().asyncStarted()).andReturn(); startedAsyncRequestProcessing.getAsyncResult(config.getAsyncConfig().timeoutInMs()); mvcResult = mockMvc.perform(asyncDispatch(startedAsyncRequestProcessing)).andReturn(); } else { mvcResult = perform.andReturn(); } return mvcResult; }
@Test public void noHttpSession() throws Exception { MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new TestController()) .apply(sharedHttpSession()) .build(); String url = "/no-session"; MvcResult result = mockMvc.perform(get(url)).andExpect(status().isOk()).andReturn(); HttpSession session = result.getRequest().getSession(false); assertNull(session); result = mockMvc.perform(get(url)).andExpect(status().isOk()).andReturn(); session = result.getRequest().getSession(false); assertNull(session); url = "/session"; result = mockMvc.perform(get(url)).andExpect(status().isOk()).andReturn(); session = result.getRequest().getSession(false); assertNotNull(session); assertEquals(1, session.getAttribute("counter")); }
@Test public void saveSpecial() throws Exception { this.mockMvc.perform(post("/people").param("name", "Andy")) .andExpect(status().isFound()) .andExpect(redirectedUrl("/persons/Joe")) .andExpect(model().size(1)) .andExpect(model().attributeExists("name")) .andExpect(flash().attributeCount(1)) .andExpect(flash().attribute("message", "success!")); }
@Test public void getWhenBookmarkedRequestIsRequestedWithAndroidThenPostAuthenticationRemembers() throws Exception { this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire(); MockHttpSession session = (MockHttpSession) this.mvc.perform(get("/messages") .header("X-Requested-With", "com.android")) .andExpect(redirectedUrl("http://localhost/login")) .andReturn().getRequest().getSession(); this.mvc.perform(formLogin(session)) .andExpect(redirectedUrl("http://localhost/messages")); }
@Test public void testContentAsString() throws Exception { this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)) .andExpect(content().string("Hello world!")); this.mockMvc.perform(get("/handleUtf8")) .andExpect(content().string("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01")); // Hamcrest matchers... this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)).andExpect(content().string(equalTo("Hello world!"))); this.mockMvc.perform(get("/handleUtf8")).andExpect(content().string(equalTo("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01"))); }
@Test public void configureWhenCustomAuthorizationRequestResolverSetThenAuthorizationRequestIncludesCustomParameters() throws Exception { // Override default resolver OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = authorizationRequestResolver; authorizationRequestResolver = mock(OAuth2AuthorizationRequestResolver.class); when(authorizationRequestResolver.resolve(any())).thenAnswer(invocation -> defaultAuthorizationRequestResolver.resolve(invocation.getArgument(0))); this.spring.register(OAuth2ClientConfig.class).autowire(); this.mockMvc.perform(get("/oauth2/authorization/registration-1")) .andExpect(status().is3xxRedirection()) .andReturn(); verify(authorizationRequestResolver).resolve(any()); }
@Test public void multipartRequestWithOptionalFileArrayNotPresent() throws Exception { byte[] json = "{\"name\":\"yeeeah\"}".getBytes(StandardCharsets.UTF_8); MockMultipartFile jsonPart = new MockMultipartFile("json", "json", "application/json", json); standaloneSetup(new MultipartController()).build() .perform(multipart("/optionalfilearray").file(jsonPart)) .andExpect(status().isFound()) .andExpect(model().attributeDoesNotExist("fileContent")) .andExpect(model().attribute("jsonContent", Collections.singletonMap("name", "yeeeah"))); }
@Test public void testResetPasswordPage() throws Exception { ExpiringCode code = codeStore.generateCode("{\"user_id\" : \"some-user-id\"}", new Timestamp(System.currentTimeMillis() + 1000000), null, IdentityZoneHolder.get().getId()); mockMvc.perform(get("/reset_password").param("email", "user@example.com").param("code", code.getCode())) .andExpect(status().isOk()) .andDo(print()) .andExpect(view().name("reset_password")) .andExpect(model().attribute("email", "email")) .andExpect(model().attribute("username", "username")) .andExpect(content().string(containsString("<div class=\"email-display\">Username: username</div>"))) .andExpect(content().string(containsString("<input type=\"hidden\" name=\"username\" value=\"username\"/>"))); }
@Test void introspectToken_withInvalidToken() throws Exception { mockMvc.perform( post("/introspect") .header("Authorization", "Basic " + basic) .header(ACCEPT, APPLICATION_JSON_VALUE) .header(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE) .param("token", "invalid-token")) .andDo(log()) .andExpect(status().isOk()) .andExpect(jsonPath("$.active").value("false")) .andExpect(header().string(CONTENT_TYPE, "application/json;charset=UTF-8")); }
@Test public void testFeedWithLinefeedChars() throws Exception { // Map<String, String> namespace = Collections.singletonMap("ns", ""); standaloneSetup(new BlogFeedController()).build() .perform(get("/blog.atom").accept(MediaType.APPLICATION_ATOM_XML)) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_ATOM_XML)) .andExpect(xpath("//feed/title").string("Test Feed")) .andExpect(xpath("//feed/icon").string("http://www.example.com/favicon.ico")); }
@Test public void servletLogoutWhenUsingDefaultConfigurationThenUsesSpringSecurity() throws Exception { this.spring.configLocations(this.xml("Simple")).autowire(); MvcResult result = this.mvc.perform(get("/good-login")).andReturn(); MockHttpSession session = (MockHttpSession) result.getRequest().getSession(false); assertThat(session).isNotNull(); result = this.mvc.perform(get("/do-logout").session(session)) .andExpect(status().isOk()) .andExpect(content().string("")) .andReturn(); session = (MockHttpSession) result.getRequest().getSession(false); assertThat(session).isNull(); }
@Test public void getPerson() throws Exception { this.mockMvc.perform(get("/persons/Joe").flashAttr("message", "success!")) .andExpect(status().isOk()) .andExpect(forwardedUrl("persons/index")) .andExpect(model().size(2)) .andExpect(model().attribute("person", new Person("Joe"))) .andExpect(model().attribute("message", "success!")) .andExpect(flash().attributeCount(0)); }
@Test public void getWhenDefaultsThenLoginChallengeCreatesSession() throws Exception { this.spring.register(DefaultConfig.class, BasicController.class).autowire(); MvcResult result = this.mvc.perform(get("/")) .andExpect(status().isUnauthorized()) .andReturn(); assertThat(result.getRequest().getSession(false)).isNotNull(); }
@Test public void logoutWhenDefaultConfigurationThenCsrfCleared() throws Exception { this.spring.configLocations( this.xml("shared-controllers"), this.xml("AutoConfig") ).autowire(); MvcResult result = this.mvc.perform(get("/csrf")).andReturn(); MockHttpSession session = (MockHttpSession) result.getRequest().getSession(); this.mvc.perform(post("/logout").session(session) .with(csrf())) .andExpect(status().isFound()); this.mvc.perform(get("/csrf").session(session)) .andExpect(csrfChanged(result)); }