我创建了过滤器,该过滤器记录并保存了所有请求,这是其中的一部分:
@Component
public class RequestFilter extends OncePerRequestFilter {
@Value("${app.endpoint}")
private String requestMapping;
private final RequestRepository requestRepository;
@Autowired
public RequestFilter(RequestRepository requestRepository) {
this.requestRepository = requestRepository;
}
....
}
在运行应用程序requestMapping
时,可以从spring上下文中正确读取它,但是
当我为该过滤器requestMapping创建测试为null
@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
@ContextConfiguration(classes = {MyApplication.class})
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class FilterTest {
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private RequestRepository requestRepository;
@Autowired
protected MockMvc mockMvc;
@Before
public void setup() {
RequestFilter rpmRequestFilter = new RequestFilter(this.requestRepository);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.addFilter(invalidVpmRequestFilter)
.build();
}
}
当然,在application-test.properties中,我已经配置了此属性:
app.endpoint=/log/save
有人知道问题可能在哪里吗?为什么这在测试中不起作用?
答案 0 :(得分:1)
正如M. Deinum所指出的那样,问题在于您正在创建RequestFilter
的实例,并且如果您想让Spring在其中注入组件(@Autowired
)或属性(@Value
它,您必须让Spring按照以下方式处理实例:
@....
public class FilterTest {
....
@Autowired
RequestFilter requestFilter;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.addFilter(requestFilter)
.build();
}
}