如何为Jersey We Services测试用例的Junit初始化JNDI上下文

时间:2019-02-26 04:13:12

标签: java junit jersey jndi jersey-test-framework

我正在为Jersey WS编写测试用例,并停留在JNDI初始化上。 获取“ javax.naming.NameNotFoundException:此上下文未绑定名称jdbc”异常。

    public class LoginServicesTest extends JerseyTest {


    @Override
    protected Application configure() {
        return new ResourceConfig(LoginServices.class);
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
        try {
            // Create initial context
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                "org.apache.naming.java.javaURLContextFactory");
            System.setProperty(Context.URL_PKG_PREFIXES,
                "org.apache.naming");
            InitialContext ic = new InitialContext();

            ic.createSubcontext("java:");
            ic.createSubcontext("java:comp");
            ic.createSubcontext("java:comp/env");


         // Construct DataSource
            OracleConnectionPoolDataSource ds = new OracleConnectionPoolDataSource();
            ds.setURL("jdbc:oracle:thin:@dbs-host.comp.com:1525:USRDEV");
            ds.setUser("DBName");
            ds.setPassword("password");
            ic.bind("java:comp/env", ds);

        } catch (NamingException ex) {ex.printStackTrace();}
    }

    @Test
    public void acceptAgreementTest() {
        Response response = target("/user/acceptAgreement").request().get();
        System.out.println(response);
    }
}

数据源创建代码:

public DataSource getDataSource() {
        DataSource dataSource = null;
        String jndiName = null;
        try {

            jndiName = "jdbc/usrdb";
            Context env = (Context) initialContext.lookup("java:comp/env");
            dataSource = (DataSource) env.lookup(jndiName);
        }catch(Exception e) {
            LOGGER.error("ServiceLocator", e);
            e.printStackTrace();
        }
        return dataSource;
    }

请提出建议,我该如何对通过JNDI具有数据库连接的Jersey WS进行测试覆盖。感谢所有解决问题的指针。严重卡住了。

0 个答案:

没有答案