【发布时间】:2021-02-08 13:49:59
【问题描述】:
我有一个 Spring Boot 应用程序,想为控制器编写集成测试。这是我的SecurityConfig:
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final MyUserDetailsService userDetailsService;
private final SessionAuthenticationProvider authenticationProvider;
private final SessionAuthenticationFilter sessionAuthenticationFilter;
@Override
public void configure(WebSecurity web) {
//...
}
@Override
protected void configure(HttpSecurity http) throws Exception {
/...
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
auth.userDetailsService(userDetailsService);
}
}
这是我的控制器:
@RestController
public class MyController {
//...
@GetMapping("/test")
public List<TestDto> getAll(){
List<TestDto> tests= testService.findAll(authService.getLoggedUser().getId());
return mapper.toTestDtos(tests);
}
}
我创建了一个测试(JUnit 5):
@WebMvcTest(TestController.class)
class TestControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean(name = "mockTestService")
private TestService testService;
@Autowired
private TestMapper mapper;
@MockBean(name = "mockAuthService")
private AuthService authService;
private Test test;
@BeforeEach
void setUp() {
User user = new Test();
user.setId("userId");
when(authService.getLoggedUser()).thenReturn(user);
test = new Facility();
test.setId("id");
test.setName("name");
when(testService.findAll("userId")).thenReturn(singletonList(test));
}
@Test
void shouldReturnAllIpaFacilitiesForCurrentTenant() throws Exception {
mockMvc.perform(get("/test").contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$..id").value(test.getId()))
.andExpect(jsonPath("$..timeOut").value(test.getName()));
}
}
当我开始测试时出现异常:Consider defining a bean of type 'com.auth.MyUserDetailsService' in your configuration.
这是因为我在测试中没有 UserDetailsService bean。我该怎么办:
-
SecurityConfig 需要添加 3 个 bean,例如:
@MockBean 我的用户详细信息服务用户详细信息服务; @MockBean SessionAuthenticationProvider 身份验证提供者; @MockBean SessionAuthenticationFilter sessionAuthenticationFilter;
-
添加 SecurityConfig 的测试实现
-
其他的
哪种方法更好?
【问题讨论】:
标签: spring-boot spring-security junit5 spring-boot-test spring-security-rest