Java 无法模拟JNDI资源

Java 无法模拟JNDI资源,java,spring,junit,jndi,junit5,Java,Spring,Junit,Jndi,Junit5,我有一个JUnit测试,我想模拟使用JNDI的数据源: @SpringBootTest(classes = Application.class) @RunWith(SpringJUnit4ClassRunner.class) public class BinCountryCheckFilterImplTest { @MockBean private static DataSource dataSource; @BeforeClass public sta

我有一个JUnit测试,我想模拟使用JNDI的数据源:

@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class BinCountryCheckFilterImplTest    {

    @MockBean
    private static DataSource dataSource;

    @BeforeClass
    public static void setupJndi() throws Exception {
        SimpleNamingContextBuilder.emptyActivatedContextBuilder();
        Context context = new InitialContext();
        context.bind("java:global/production", dataSource);
    }

    @BeforeEach
    public void beforeEachTest() throws IOException {
        ......
    }

    @Test
    public void testBinCountryCheckFilterImpl() throws JsonProcessingException, JAXBException {
         ...
    }    
}
当我运行ode时,我得到一个错误:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException: Failed to look up JNDI DataSource with name 'java:global/production'; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or in an application resource file: java.naming.factory.initial
 Failed to look up JNDI DataSource with name 'java:global/production'; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or in an application resource file: java.naming.factory.initial

您知道如何解决此问题吗?

您可能需要阅读。如果您只编写
global/production
(不带
java:
前缀),它能工作吗?通常在EJB容器中,您将JDBC数据源定义为
JDBC/
,然后用相同的字符串引用它们。在容器外部,您可能必须在查找中使用
java:comp/env/jdbc/
。您收到的错误消息似乎暗示您没有活动的JNDI提供程序。绑定后是否需要调用
SimpleNameingContextBuilder.activate()
?还请注意,SimpleNameingContextBuilder已被弃用。你应该改用。我很高兴。