0

我正在关注本教程:https ://cwiki.apache.org/confluence/display/CXF20DOC/JAXRS+Testing

但我得到这个错误:

javax.naming.NoInitialContextException:需要在环境或系统属性中指定类名,或作为小程序参数,或在应用程序资源文件中: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) {

..

4

1 回答 1

0

问题很可能是因为您在未配置 JNDI 服务器的 Java SE 环境中运行测试。如果您在 Java EE 应用程序服务器中将测试作为 WAR 的一部分运行,这可能工作得很好。

因此,您可能需要在应用程序服务器中运行单元测试,或者您可以尝试像此处描述的那样模拟 JNDI 服务器:http: //en.newinstance.it/2009/03/27/mocking-jndi/#

希望这会有所帮助,安迪

于 2017-09-16T00:25:49.327 回答