如何在构造函数中使用存储库模拟过滤器?

时间:2018-08-21 06:43:01

标签: spring spring-mvc spring-boot

我创建了保存异常请求的过滤器,并且此过滤器在构造函数中具有存储库:

@Component
public class LogRequestsFilter extends OncePerRequestFilter {

    private final LogRepository logRepository;

    @Autowired
    public LogRequestsFilter(LogRepository logRepository) {
        this.logRepository = logRepository;
    }

我正在尝试创建一个测试,就像之前在控制器类中所做的一样,但是我无法添加过滤器:

    @SpyBean
    private LogRepository logRepository;


    @Before
    public void setup(){
        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                .addFilters(new LogRequestsFilter(this.logRepository), "/*")
                .build();
    }

这给了我错误:

Inferred type 'T' for type parameter 'T' is not within its bound; 
should extend 'org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder

1 个答案:

答案 0 :(得分:1)

非常感谢@ M.DEinum和@JB Nizet,我创建了工作解决方案:

    @Autowired
    private LogRepository logRepository;


    @Before
    public void setup(){
        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
LogRequestsFilter(this.logRepository), "/*")
                .build();
    }