'Why is OpenLiberty datasource not available in unit tests?

OpenLiberty is running in dev-mode. Somewhere in my code i use

Context initContext = new InitialContext();
DataSource ds = (DataSource) initContext.lookup("app/myDB");

with a datasource configured in the webserver:

<dataSource id="mssql" jndiName="app/myDB">
    <connectionManager maxPoolSize="20000" minPoolSize="2"/>

    <jdbcDriver libraryRef="MSSQL"/>
    <properties.microsoft.sqlserver databaseName="myDB" serverName="xxx.xxx.xxx.xxx" portNumber="1433" user="X" password="Y"/>
</dataSource>

This works fine so far, until i try to run my units tests.

When trying to run the tests on demand, that somewhere call this code:

Context initContext = new InitialContext();
DataSource ds = (DataSource) initContext.lookup("app/myDB");

my webapp fails with

javax.naming.NoInitialContextException

So why do the unit tests do not have the initial context? Can i somehow tell OpenLiberty to provide that resource for test scope? Or do i have to mock the initialContext? I am a beginner in writing unit/integration test. If i need to provide additional information please tell me.

edit: added dev-mode and general clarification



Solution 1:[1]

In order for a DataSource to be made available for JNDI lookups in Liberty, you need to have the Liberty server running and the jndi-1.0 feature enabled, and one of the jdbc-4.x features enabled. For example, in server.xml,

<<server>
    <featureManager>
        <feature>jndi-1.0</feature>
        <feature>jdbc-4.2</feature>
        ... other features
    </featureManager>

    ...
</server>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 njr