How can I bind a DataSource to an InitialContext for JUnit testing? [duplicate]

别来无恙 提交于 2019-11-28 05:29:05

When I last tried something like this a few years ago, I finally gave up and refactored: at that point, you could NOT create a DataSource outside of a container. Maybe you can, now, maybe someone's mocked something up.

Still, that smells... You shouldn't have ANY "business logic" code directly dependent on DataSources or JNDI lookups or such. That's all plumbing to be wired together outside your code.

How flexible is your design? If your code under test is directly dependent on a DataSource (or even obtains its own Connection), refactor it. Injecting a Connection will let you can test all you like with plain old JDBC, even using an in-memory implementation, and save you from having to prop up a lot of unnecessary (for the test, anyway) infrastructure to do it.

I found that example to be wrong as well. This worked for me.

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

final PGSimpleDataSource ds = new PGSimpleDataSource();
ds.setUrl("jdbc:postgresql://localhost:5432/mydb");
ds.setUser("postgres");
ds.setPassword("pg");

ic.bind("java:comp/env/jdbc/mydb", ds);

The difference you'll note is that the '/' after 'java:' in each of the contexts is wrong and shouldn't be there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!