Spring Securityを使ってるSpring BootのWebアプリでテストを書く時に、認証自体をテストしたいのでなければ spring-security-test
で認証情報を簡単にMockできる。
pom.xml
spring-security-test
を dependency
に追加する
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency>
@WithMockUser
@WithMockUser
をテストメソッドに付与することで、認証情報をモックできる。
ユーザ名やROLEも簡単にMockできそうである。
@RunWith(SpringRunner.class) @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringbootWebSampleApplication.class) @AutoConfigureMockMvc public class CustomerControllerIntegrationTest { @Autowired private MockMvc mvc; @Test @WithMockUser public void whenGetCustomers_thenStatus200() throws Exception { mvc.perform(get("/customers")) .andExpect(status().isOk()); } }
まとめ
なんかすごい見当違いの方向でがんばってたんだけど、Spring Security使ってるなら、spring-security-test
に便利なものいろいろあるからそれ使えばいいってだけの話だった気がする。