java 您如何使用 JUNIT 测试 spring jdbcTemplate?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13224036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:56:42  来源:igfitidea点击:

How do you test a spring jdbcTemplate with JUNIT?

javaspringjunitdatasourcejdbctemplate

提问by E Paiz

I have a DAO that I'm trying to test that uses a jdbcTemplate. The spring jdbcTemplate has a datasoruce attribute on it that needs to be set for it to work. However, when a JUNIT test runs the datasource does not exist and the bean creation fails. How can I set up the datasource of the jdbcTemplate to work in the JUNIT test case?

我有一个我正在尝试使用 jdbcTemplate 测试的 DAO。spring jdbcTemplate 上有一个 datasoruce 属性,需要对其进行设置才能使其工作。但是,当 JUNIT 测试运行时,数据源不存在并且 bean 创建失败。如何设置 jdbcTemplate 的数据源以在 JUNIT 测试用例中工作?

Any help is appreciated.

任何帮助表示赞赏。

Thanks

谢谢

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'thisDatasource' defined in class path resource [userDataBaseContext.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    ... 33 more
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
    at javax.naming.InitialContext.lookup(InitialContext.java:392)
    at org.springframework.jndi.JndiTemplate.doInContext(JndiTemplate.java:154)
    at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
    at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
    at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178)
    at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
    at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105)
    at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:201)
    at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:187)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1479)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
    ... 40 more

采纳答案by E Paiz

I solved my problem using information from the following link:

我使用以下链接中的信息解决了我的问题:

How to test a mocked JNDI datasource with Spring?

如何使用 Spring 测试模拟的 JNDI 数据源?

Instead of using the datasource defined in my spring files, I just created a new datasource:

我没有使用 spring 文件中定义的数据源,而是创建了一个新的数据源:

<bean id="thisDatasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
p:url="jdbc:sqlserver://sqlserver:1234;databaseName=myTables"
p:username="userid"
p:password="passw0rd" /> 


<bean id="databaseUserDAOTest" 
class="com.spring.security.custom.user.detail.DatabaseUserDAO" >
<!-- Inject the datasource of the jdbcTemplate -->
<property name="dataSource" ref="thisDatasource" />        
</bean>

回答by Kevin Bowersox

Use the Spring Testing Framework. It allows your unit test to leverage a Spring Container configured for your application-context. Once setup you can use @Autowired on your datasource to inject the datasource required to test the jdbcTemplate.

使用Spring 测试框架。它允许您的单元测试利用为您的应用程序上下文配置的 Spring Container。设置完成后,您可以在数据源上使用 @Autowired 来注入测试 jdbcTemplate 所需的数据源。

Here is an example of one of my test using Spring-Data.

这是我使用 Spring-Data 进行的测试之一的示例。

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import org.tothought.entities.Post;
import org.tothought.entities.PostPart;
import org.tothought.entities.Tag;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@Transactional
public class PostRepositoryTest {

    @Autowired 
    TagRepository tagRepository;

    @Test
    public void findOneTest() {
        Post post = repository.findOne(1);
        assertNotNull(post);
        assertTrue(post.getTags().size()>1);
    }
}

Notice the @ContextConfigurationannotation. This annotation points to the context used to setup the Spring container, which I then inject my repository from. Since I have not specified a name for my context Spring searches for a configuration file within the same directory as my test class that has the name PostRepositoryTest-context.xml. This setup is described in more detail in the documentation provided above.

注意@ContextConfiguration注释。此注释指向用于设置 Spring 容器的上下文,然后我从中注入我的存储库。由于我没有为我的上下文指定名称,Spring 会在与我的测试类相同的目录中搜索一个名为 PostRepositoryTest-context.xml 的配置文件。上面提供的文档中更详细地描述了此设置。

To begin using the project include the following in your pom.xml file.

要开始使用该项目,请在 pom.xml 文件中包含以下内容。

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>