mockmvc

Spring security not calling my custom authentication filter when running JUnit tests

偶尔善良 提交于 2019-12-05 04:55:11
I'm trying to implement custom stateless authentication with Spring Security by following this article The problem I'm facing is that my custom filter is not being called by the framework, even when my SecurityConfig looks almost the same as in the previous link (a bit simpler): @Configuration @EnableWebMvcSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired @Qualifier("appAuthenticationProvider") private AuthenticationProvider authenticationProvider; @Autowired @Qualifier("appAuthenticationFilter") private

spring 4.1.1, mockmvc and do not want url encoding of HTTP GET request

匆匆过客 提交于 2019-12-05 04:44:05
Using MockMVC in tests and I need to test a GET URL that is already URL encoded: http://host:port/app/controller/[ALREADY URL ENCODED] The code: mockmvc.perform(get("/controller/[ALREADY URL ENCODED]") However in the logs I see that the URL has been url encoded again before it gets to the appropriate controller method. Is there a way that we can prevent spring mockmvc to url encode? Perhaps disable url encoding in the test? Real example of the "[ALREADY URL ENCODED]" string: MEUwQzBBMD8wPTAJBgUrDgMCGgUABBQ%2Fm36Fj2BE19VBYXRO62zrgIYp0gQVAQazEyvlq22wsMBkRyAeaUiZ%2BhTUAgMGJbQ%3D This gets URL

Unit Testing /login in Spring MVC using MockMvc

戏子无情 提交于 2019-12-05 02:26:13
I have a very simple REST application created using Spring MVC. (Code is available at GitHub .) It has a simple WebSecurityConfigurer as follows: @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity .csrf().disable() .exceptionHandling() .authenticationEntryPoint(authenticationEntryPoint) .and() .authorizeRequests() .antMatchers("/user/new").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login").permitAll() .successHandler(authenticationSuccessHandler) .failureHandler(authenticationFailureHandler) .and() .logout() .permitAll(

Upload file using Spring mvc and MockMVC

若如初见. 提交于 2019-12-05 02:09:39
I have successfully uploaded a image file to WebContent\resources\uploads\image.jsp . But I am facing a problem in testing this using MockMvc. When I run the test case I am getting the exceptions file not found and access denied . The controller looks like this: @RequestMapping(value="/AddContacts", method=RequestMethod.POST) public @ResponseBody String addContacts(ContactBean cb,HttpServletRequest request,HttpServletResponse response,@RequestParam("upload") MultipartFile file) throws IllegalStateException, IOException { String error=cb.validate(); if(error.equals("")){ Model m=new Model();

How to prevent NestedServletException when testing Spring endpoints?

六月ゝ 毕业季﹏ 提交于 2019-12-04 17:43:26
问题 I am trying to test the security configuration of some of my endpoints which are secured with @PreAuthorize(#oauth2.hasScope('scope') . When accessing such an endpoint via Postman with a access token that does not have the required scope, the following is returned with HTTP status code 403 (forbidden): { "error": "insufficient_scope", "error_description": "Insufficient scope for this resource", "scope": "scope" } Which is the expected behaviour that I want. When trying to test this

Spring Security, JUnit: @WithUserDetails for user created in @Before

微笑、不失礼 提交于 2019-12-04 17:28:32
问题 In JUnit tests with Spring MockMVC, there are two methods for authenticating as a Spring Security user: @WithMockUser creates a dummy user with the provided credentials, @WithUserDetails takes a user's name and resolves it to the correct custom UserDetails implementation with a custom UserDetailsService (the UserDetailsServiceImpl ). In my case, the UserDetailsService loads an user from the database. The user I want to use was inserted in the @Before method of the test suite. However, my

Hamcrest with MockMvc: check that key exists but value may be null

假装没事ソ 提交于 2019-12-04 10:40:27
问题 I'm doing some tests with MockMvc, and I want to validate the structure of a JSON response. Specifically, I want to make sure that the key to an attribute exists, and that the value is of a certain type or null. { "keyToNull": null, # This may be null, or a String "keyToString": "some value" } The following works for me, but I'm wondering if there's a way to combine each group of two expectations into a single line, as I have a lot of attributes to check: import static org.springframework

How to test if JSON path does not include a specific element, or if the element is present it is null?

梦想与她 提交于 2019-12-04 09:50:00
问题 I have been writing some simple unit testing routines for a simple spring web application. When I add @JsonIgnore annotation on a getter method of a resource, the resulting json object does not include the corresponding json element. So when my unit test routine tries to test if this is null (which is the expected behavior for my case, I don't want the password to be available in json object), test routine runs into an exception: java.lang.AssertionError: No value for JSON path: $.password,

MockRestServiceServer simulate backend timeout in integration test

霸气de小男生 提交于 2019-12-04 00:45:42
I am writing some kind of integration test on my REST controller using MockRestServiceServer to mock backend behaviour. What I am trying to achieve now is to simulate very slow response from backend which would finally lead to timeout in my application. It seems that it can be implemented with WireMock but at the moment I would like to stick to MockRestServiceServer. I am creating server like this: myMock = MockRestServiceServer.createServer(asyncRestTemplate); And then I'm mocking my backend behaviour like: myMock.expect(requestTo("http://myfakeurl.blabla")) .andExpect(method(HttpMethod.GET))

mockMvc - Test Error Message

烈酒焚心 提交于 2019-12-03 23:00:55
Does anybody have any tips, or does anybody know how I can test the "error message" returned by the HTTP response object? @Autowired private WebApplicationContext ctx; private MockMvc mockMvc; @Before public void setUp() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build(); } Response: MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[application/json;charset=UTF-8]} Content type = application/json;charset=UTF-8 You can use the method status.reason() . For example: @Test public void loginWithBadCredentials() { this.mockMvc.perform( post