In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
SpringSecurity unit testing is how, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
Today, the newcomer in the group asked me confused: brother, I can't run the unit test because of Spring Security. It's always 401. Let's see how to solve it. No problem, there is the awareness of writing unit tests, the quality of the code written must be guaranteed, the attitude of attaching importance to code quality, this kind of help must be helped!
Spring Security test environment
To use Spring Security in unit tests, you need to integrate into the Spring Boot project:
Org.springframework.security spring-security-test test
In this way, the context configuration of the test can be combined with Spring Security, and then I'll teach you a few tips.
Spring Security test
All tests are done under SpringBootTest, which is supported by the @ SpringBootTest annotation.
@ WithMockUser
The @ WithMockUser annotation can help us simulate a user with a default name of user, a default password of password, and a default role of USER in the Spring Security security context. When your test method uses this annotation, you can pass:
Authentication authentication = SecurityContextHolder.getContext () .getAuthentication ()
To get the information about the simulated user, you "pretend" that you are currently logged in to the user user. Of course, you can also customize user names, passwords, and roles as needed:
SneakyThrows @ Test @ WithMockUser (username = "felord", password = "felord.cn", roles = {"ADMIN"}) void updatePassword () {mockMvc.perform (post ("/ user/update/password") .contentType (MediaType.APPLICATION_JSON) .content ("{\ n" + "\" newPassword\ ":\" 12345\ " \ n "+"\ "oldPassword\":\ "12345\"\ n "+"} ") .andexpect (ResultMatcher.matchAll (status (). IsOk () .andDo (print ()) }
Of course, you can mark @ WithMockUser on the entire test class, so that each test will use the specified user.
@ WithAnonymousUser
@ WithAnonymousUser is used to impersonate a special type of user, also known as anonymous user. If there is a need to test anonymous users, you can use this annotation directly. In fact, it is equivalent to @ WithMockUser (roles = {"ANONYMOUS"}) and @ WithMockUser (authorities = {"ROLE_ANONYMOUS"}). You should be able to see the difference carefully.
@ WithUserDetails
Although @ WithMockUser is a very convenient way, it may not work in all cases. Sometimes you change something to change the authentication mechanism of the security context, such as if you customize UserDetails, this kind of annotation is not good. But users loaded through UserDetailsService tend to be reliable. So @ WithUserDetails came in handy.
@ SneakyThrows @ Test @ WithUserDetails ("felord") void updatePassword () {mockMvc.perform (post ("/ user/update/password") .contentType (MediaType.APPLICATION_JSON) .content ("{\ n" + "\" newPassword\ ":\" 12345\ " \ n "+"\ "oldPassword\":\ "12345\"\ n "+"} ") .andexpect (ResultMatcher.matchAll (status (). IsOk () .andDo (print ()) }
When we perform the unit test, we will find the user with the user name felord through the loadUserByUsername method of UserDetailsService and load it into the security context.
Custom annotation
Actually, we can simulate @ WithMockUser.
Target ({ElementType.METHOD, ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Inherited @ Documented @ WithSecurityContext (factory = WithMockUserSecurityContextFactory.class) public @ interface WithMockUser {String value () default "user"; String username () default ""; String [] roles () default {"USER"}; String [] authorities () default {}; String password () default "password"; @ AliasFor (annotation = WithSecurityContext.class) TestExecutionEvent setupBefore () default TestExecutionEvent.TEST_METHOD;}
The key is the @ WithSecurityContext annotation. We just need to implement factory, that is:
Public interface WithSecurityContextFactory {SecurityContext createSecurityContext (An annotation);}
Just do the same here, and we won't demonstrate it if it's not difficult.
Today we show how to unit test when you integrate Spring Security into your application. We can use the provided comments to simulate the user, or you can simulate and load the user, and you can even customize it according to your own needs. In fact, if you use JWT, then there is a wild way, you can add the corresponding request headers or parameters to the Spring MVC Mock test, and it can also proceed smoothly.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.