这是我的 REST 资源:
@Context
HttpServletRequest webRequest;
@Override
public DomainConfig get() {
return configDelegate.get(webRequest.getHeader("Origin"));
}
我已经使用 Junit 5 + Weld / Mockito 扩展构建了我的单元测试。
@MockitoSettings(strictness = Strictness.STRICT_STUBS)
@ExtendWith(MockitoExtension.class)
@DisplayName("configs resource")
@EnableWeld
public class ConfigApiResourceTest {
@Mock
HttpServletRequest servletRequest;
@WeldSetup
public WeldInitiator weld = WeldInitiator
.from(
MockCommonResources.class,
ConfigApiResource.class,
ConfigDelegate.class,
ConfigService.class,
etc etc
)
.addBeans(createHttpServletRequest())
.activate(
RequestScoped.class,
ApplicationScoped.class
)
.build();
Bean<?> createHttpServletRequest() {
return MockBean.builder()
.types(HttpServletRequest.class)
.create(o -> servletRequest)
.build();
}
@Test
@DisplayName("config")
void config(ConfigApiResource configApiResource) {
final String url = "areaclient.infocert.it";
when(servletRequest.getHeader("Origin")).thenReturn(url);
final DomainConfig output = configApiResource.get();
assertNotNull(output);
}
}
问题是 HttpServletRequest webRequest 始终为空,可能是因为未注入但它是上下文对象。
所以真正的问题是,我怎样才能生成一个 HttpServletRequest 模拟并作为 @Context 对象注入?