运行测试时自动连接userdetailsservice时出现问题

mwecs4sa  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(275)

我将Spring Security 添加到我的应用程序中,它运行得很好,但现在现有的测试已被破坏,当我运行它们时,我得到:


***************************

APPLICATION FAILED TO START

***************************

Description:

Field userDetailsService in xxx.xxx.someapp.spring.security.WebSecurityConfig required a bean of type 'xxx.xxx.sardinatank.someapp.security.services.UserDetailsServiceImpl' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

这就是我在WebSecurity配置中连接userdetailsserviceimpl的方式

@Autowired
UserDetailsServiceImpl userDetailsService;

这是一个示例控制器

@RestController
public class HelloWorldController {

  @GetMapping
  public ModelAndView helloWorld() {
    final ModelAndView bootstrapFront = new ModelAndView("index.html");
    return bootstrapFront;
  }
}

这是一个失败的测试

@WebMvcTest(controllers = HelloWorldController.class)
@ContextConfiguration
@WebAppConfiguration
class HelloWorldControllerTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @BeforeEach
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void getBootstrappedDoc() throws Exception {
        MvcResult mvcResult = mockMvc.perform(get("/"))
            .andExpect(status().isOk())
            .andReturn();
        assertEquals("index.html", mvcResult.getModelAndView().getViewName());
    }
}
wj8zmpe1

wj8zmpe11#

我想你可能已经宣布了 @Component 或者不在这个列表中的东西: @Controller , @ControllerAdvice , @JsonComponent , Converter , Filter , WebMvcConfigurer 这意味着 UserdetailServiceImpl 将不属于 @SpringWebMVC 切片测试上下文,因此spring不会引导它。
您有两种选择:
要么你装饰你的房间 UserServiceImpl 使用上述注解之一:例如

@JsonComponent
  class UserDetailsServiceImpl implements userDetailsService { ... };

或者在测试中使用 @MockBean :

@WebMvcTest(controllers = HelloWorldController.class)
@ContextConfiguration
@WebAppConfiguration
class HelloWorldControllerTest {

  @Autowired
  private WebApplicationContext webApplicationContext;

  @MockBean
  UserDetailsServiceImpl userDetailsService;

  private MockMvc mockMvc;

  //...

}

相关问题