我正在关注本教程:https://cwiki.apache.org/confluence/display/CXF20DOC/JAXRS+Testing
但是我收到了这个错误:
javax.naming.NoInitialContextException:需要在环境或系统属性中指定类名,或在applet参数中或在应用程序资源文件中指定类名:java.naming.factory.initial
这是我的本地服务器类:
public class CXFLocalTransportTestSuite {
public static final Logger LOGGER = LogManager.getLogger();
public static final String ENDPOINT_ADDRESS = "local://service0";
private static Server server;
@BeforeClass
public static void initialize() throws Exception {
startServer();
}
private static void startServer() throws Exception {
JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
factory.setAddress(ENDPOINT_ADDRESS);
List<Class<?>> resourceClasses = new ArrayList<Class<?>>();
resourceClasses.add(CommunicationWSRESTImpl.class);
factory.setResourceClasses(resourceClasses);
List<ResourceProvider> resourceProviders = new ArrayList<>();
resourceProviders.add(new SingletonResourceProvider(new CommunicationWSRESTImpl()));
factory.setResourceProviders(resourceProviders);
List<Object> providers = new ArrayList<Object>();
providers.add(new JacksonJaxbJsonProvider());
providers.add(new ApiOriginFilter());
providers.add(new AuthenticationFilter());
providers.add(new AuthorizationFilter());
factory.setProviders(providers);
server = factory.create();
server.start();
LOGGER.info("LOCAL TRANSPORT STARTED");
}
@AfterClass
public static void destroy() throws Exception {
server.stop();
server.destroy();
LOGGER.info("LOCAL TRANSPORT STOPPED");
}
}
客户端示例:
public class CommunicationApiTest {
// [PUBLIC PROFILE]
// --------------------------------------------------------------------------------------------------------
@Test
public void getLinkedComponentsTest() {
// PATH. PARAM.
// ********************************************************************************************************
String userId = "1";
String componentInstance = "a3449197-cc72-49eb-bc14-5d43a80dfa80";
String portId = "00";
// ********************************************************************************************************
WebClient client = WebClient.create(CXFLocalTransportTestSuite.ENDPOINT_ADDRESS);
client.path("/communication/getLinkedComponents/{userId}-{componentInstance}-{portId}", userId, componentInstance, portId);
client.header("Authorization", "Bearer " + CXFLocalTransportTestSuite.authenticationTokenPublicProfile);
Response res = client.get();
if (null != res) {
assertEquals(StatusCode.SUCCESSFUL_OPERATION.getStatusCode(), res.getStatus());
assertNotNull(res.getEntity());
// VALID RESPONSE
// ********************************************************************************************************
assertEquals("> Modules has not been initialized for userID = 1", res.readEntity(GetLinksResult.class).getMessage());
// ********************************************************************************************************
}
}
}
最后,这是服务器端的jax-rs实现:
@Path("/communication")
public class CommunicationWSRESTImpl implements CommunicationWS {
@Path("/getLinkedComponents/{userId}-{componentInstance}-{portId}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getLinkedComponents(
@HeaderParam("Authorization") String accessToken,
@PathParam("userId") String userId,
@PathParam("componentInstance") String componentInstance,
@PathParam("portId") String portId) {
LOGGER.info("[CommunicationWSREST - getLinksComponents] userId: " + userId + " -- componentInstace: "
+ componentInstance + " -- portId: " + portId);
GetLinksResult result = new GetLinksResult();
result.setGotten(false);
result.setPortList(null);
if (userId != null && userId.compareTo("") != 0) {
if (componentInstance != null && componentInstance.compareTo("") != 0) {
if (portId != null && portId.compareTo("") != 0) {
TMM tmm = null;
javax.naming.Context initialContext;
try {
initialContext = new InitialContext();
tmm = (TMM) initialContext.lookup("java:app/cos/TMM");
result = tmm.calculateConnectedPorts(userId, componentInstance, portId);
} catch (Exception e) {
LOGGER.error(e);
result.setMessage("> Internal Server Error");
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build();
}
} else {
LOGGER.error("Not found or Empty Port Error");
result.setMessage("> Not found or Empty Port Error");
return Response.status(Status.NOT_FOUND).entity(result).build();
}
} else {
LOGGER.error("Not found or Empty Component Instance Error");
result.setMessage("> Not found or Empty Component Instance Error");
return Response.status(Status.NOT_FOUND).entity(result).build();
}
} else {
LOGGER.error("Not found or Empty userid Error");
result.setMessage("> Not found or Empty username Error");
return Response.status(Status.NOT_FOUND).entity(result).build();
}
return Response.ok(result).build();
}
}
可能问题是本地传输没有正确配置因为查找而启动异常(参见:服务器端):
TMM tmm = null;
javax.naming.Context initialContext;
try {
initialContext = new InitialContext();
tmm = (TMM) initialContext.lookup("java:app/cos/TMM");
result = tmm.calculateConnectedPorts(userId, componentInstance, portId);
} catch (Exception e) {
...
答案 0 :(得分:0)
问题很可能是因为您在未配置JNDI服务器的Java SE环境中运行测试。如果您在Java EE应用服务器中将测试作为WAR的一部分运行,那么这可能会正常工作。
因此,您可能需要在应用服务器内运行单元测试,或者您可以尝试模拟JNDI服务器,如此处所述:http://en.newinstance.it/2009/03/27/mocking-jndi/#
希望这有帮助, 安迪