首页 > 解决方案 > Spring Securities 测试找不到 Bean 错误

问题描述

我正在使用以下代码来测试带有 Spring 证券的 rest 控制器。WebMvcTest 用于执行测试。我不想使用 SpringBootTest 注释,因为它会使测试在启动整个应用程序上下文时变得非常缓慢。

package org.project.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.project.model.SampleBean;
import org.project.service.SampleBeanService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class) // tells JUnit to run using Spring’s testing support.
@WebMvcTest(SampleBeanRestController.class)
@AutoConfigureMockMvc
public class SampleBeanRestControllerTest  {

   @MockBean
   private SampleBeanService SampleBeanService;

   @Autowired
   private MockMvc mockMvc;

   public MockMvc getMockMvc() {
      return mockMvc;
   }

   @Test
   @WithMockUser(username = "user", password = "password", roles = "USER")
   public void deleteSampleById() throws Exception{
      getMockMvc().perform(delete("/api/sample/1")
         .contentType(MediaType.APPLICATION_JSON))
         .andExpect(status().isOk());
   }

}

我收到以下错误:

Parameter 0 of constructor in org.project.config.WebSecurityConfig required a bean of type 'org.project.security.jwt.TokenProvider' that could not be found.

我怎样才能绕过这个?WebSecurityConfig 中已导入 TokenProvider。谢谢。

标签: javaspring-bootjunitspring-security

解决方案


实际上,@WebMvcTest测试只关注 Spring MVC 组件。

您的@WebMvcTest上下文中缺少 bean 定义。因为您没有使用@SpringBootTest所有与 Spring MVC 上下文无关的组件(例如@Component@Service@Repositorybean)。

因此,您需要TokenProvider另外添加组件,并且如果您还有其他依赖于 MVC 的 bean:

@TestConfiguration
public class SampleBeanRestControllerTestConfig {

    @Bean
    public TokenProvider tokenProvider() {
        return new TokenProvider();
    }

}

接下来,导入您的测试配置:

@RunWith(SpringRunner.class)
@Import(SampleBeanRestControllerTestConfig.class)
@WebMvcTest(SampleBeanRestController.class)
@AutoConfigureMockMvc
public class SampleBeanRestControllerTest  {

   //...

}

TokenProvider除非有其他依赖项,否则这应该有效。如果是这样,您还需要将它们创建为@Beans。@MockBean或者,如果有意义,您可以考虑手动使用或模拟它们。

希望能帮助到你。


推荐阅读