我正在为我的 jax-rs 服务编写一些集成测试,其中我有一组异常映射器。因此,在执行给定请求时,我期望基于异常映射器的特定响应代码。问题是在此环境中运行时我无法调用异常映射器。
我的服务应该在我的测试中引发逻辑异常:
@Stateless
@Path("/baseCustomer")
public class BaseCustomerService {
@EJB //this one gets mocked in the unittest
private BaseCustomerManagerBean customerManager;
@POST
@Path("crud")
@Consumes({MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_XML, MediaType.TEXT_XML})
public Hkunde createCustomer(Hkunde newCustomer) throws LogicalException {
//throws exception according to mocking
return customerManager.createCustomer(newCustomer);
}
和异常映射器:
@Provider
public class LogicalExceptionMapper implements ExceptionMapper<LogicalException> {
@Override
public Response toResponse(LogicalException exception) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
我这样设置我的测试:
@Mock
private BaseCustomerManagerBean baseCustomerManager;
private HttpClient httpClient;
private BaseCustomerServiceClient client;
@Configuration
public Properties config() throws Exception {
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.RemoteInitialContextFactory");
properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, Boolean.TRUE.toString());
properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, LogicalExceptionMapper.class.getName());
properties.setProperty("openejb.jaxrs.providers.auto", "true");
properties.setProperty("openejb.servicemanager.enabled", "true");
return properties;
}
@MockInjector
public Class<?> mockitoInjector() {
return MockitoInjector.class;
}
@Module
public EjbModule createModule() throws Exception {
final StatelessBean bean = (StatelessBean) new StatelessBean(BaseCustomerService.class).localBean();
bean.setRestService(true);
final EjbJar ejbJar = new EjbJar();
ejbJar.addEnterpriseBean(bean);
final OpenejbJar openejbJar = new OpenejbJar();
openejbJar.addEjbDeployment(new EjbDeployment(ejbJar.getEnterpriseBeans()[0]));
EjbModule module = new EjbModule(ejbJar);
module.setOpenejbJar(openejbJar);
return module;
}
@Module
public Class[] exceptionMappers() {
return new Class[]{LogicalExceptionMapper.class};
}
@Before
public void setup() {
ServiceHost serviceHost = new ServiceHost("http://localhost:4204/BaseCustomerServiceTest");
httpClient = new HttpClient(serviceHost);
client = new BaseCustomerServiceClient(httpClient);
}
@Test
public void createCustomer_givenLogicalException_expectsLogicalException() throws LogicalException {
Hkunde expected = new Hkunde(true);
when(baseCustomerManager.createCustomer(expected)).thenThrow(new LogicalException("mock"));
try {
client.createCustomer(expected);
fail("Expected LogicalException");
} catch (LogicalException ex) {
}
verify(baseCustomerManager).createCustomer(expected);
}
因此,当我执行测试时,我client
会从响应中读取响应代码,并根据此代码抛出异常。
问题是异常映射器从未被调用,并且我总是收到 500 内部服务器错误,而不是“禁止”响应。我猜我需要在设置 ejbjar 或类似的东西时添加更多信息。
谢谢!