How to obtain JNDI data source for JPA/JTA DAO integration test?

别等时光非礼了梦想. 提交于 2019-12-04 16:06:58
Pascal Thivent

I didn't experiment this myself but it is doable with a standalone transaction manager and a XA compliant datasource. With Spring 2.5, most samples use JOTM and the JotmFactoryBean and the XAPool. But these are non longer supported in Spring 3.0 and Atomikos appears to be the "replacement" (it provides a standalone transaction manager and a XA datasource). I've added some configuration samples below.

The alternative would be to run in-container tests (using an embedded Java EE container e.g. GlassFish v3 Embedded or an API like Cargo).

Resources

I ran into a similar problem myself. I'm using Spring with JPA and specifying my database as a JNDI name. Eventually I decided to just mock out JNDI using Mockito. This was pretty easy. Here is how I did it:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-config.xml"})
public class MyTestClass {

    private static final InitialContextFactoryBuilder contextFactoryBuilder = mock(InitialContextFactoryBuilder.class);
    private static final InitialContextFactory contextFactory = mock(InitialContextFactory.class);
    private static final Context context = mock(Context.class);
    private static final NameParser parser = mock(NameParser.class);
    private static final Name dbName = mock(Name.class);
    // This is the Datasource implementation from the H2 database
    private static final JdbcDataSource temporaryDbForTesting = new JdbcDataSource();

    @BeforeClass
    public static void setupMockJndi() throws NamingException {
        NamingManager.setInitialContextFactoryBuilder(contextFactoryBuilder);
        when(contextFactoryBuilder.createInitialContextFactory(any(Hashtable.class))).thenReturn(contextFactory);
        when(contextFactory.getInitialContext(any(Hashtable.class))).thenReturn(context);
        when(context.getNameParser(any(String.class))).thenReturn(parser);
        when(parser.parse("GatewayDbDataSource")).thenReturn(dbName);
        when(context.lookup(dbName)).thenReturn(temporaryDbForTesting);

        temporaryDbForTesting.setURL("jdbc:h2:~/test2");
        temporaryDbForTesting.setUser("sa");
        temporaryDbForTesting.setPassword("");
    }

    @Autowired
    private org.zzz.DomainObject toTest;

    @Test
    public void testPasswordChecking() {
        assertNotNull("There wasn't an object to test. Spring is broken!", toTest);
        // ... assertions and such ...
    }

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