2014-09-12 29 views
0

我正在通過一些框架來測試這個,從我可以告訴的是,似乎有很多折舊。大部分代碼似乎都指向了這個SimpleJdbcTemplate類,該類從Spring 3.1開始折舊。在模擬數據庫連接時有沒有其他的選擇?如何使用spring框架測試JDBC代碼?

我的目標是能夠編寫不依賴數據庫存在的測試用例。我正在使用Spring 3.1和Java 7.我給出的數據庫是一個SQL數據庫。

+2

Hi @Kubunto,您是否考慮過使用內存數據庫進行測試? – gerardribas 2014-09-12 13:02:59

+0

這將如何工作@gerardribas? – Kubunto 2014-09-12 13:03:44

+0

@NathanHughes,令人遺憾的是,我所知道的是,它是一個SQL數據庫,我無法以有意義的方式直接操作(例如創建一個新的或影響其結構) – Kubunto 2014-09-12 13:32:05

回答

0

您可以嘗試類似H2http://www.h2database.com/html/main.html

db.driverClassName=org.h2.Driver 
db.url=jdbc:h2:mem:test 
db.username= 
db.password= 
db.dialect=org.hibernate.dialect.H2Dialect 

HSQLhttp://hsqldb.org/

db.dialect=org.hibernate.dialect.HSQLDialect 
+0

我已經得到了一個數據庫,我不控制它是什麼樣的數據庫@Suvasis – Kubunto 2014-09-12 13:16:49

0

有關使用Spring JDBC來實現我的DAO層加速測試中,我使用的內存數據庫。

如果您正在使用maven這些都是你所需要的相關性:

<dependency> 
    <groupId>org.hsqldb</groupId> 
    <artifactId>hsqldb</artifactId> 
    <version>2.3.2</version> 
    <scope>test</scope> 
</dependency> 
<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-test</artifactId> 
    <version>${org.springframework-version}</version> 
    <scope>test</scope> 
</dependency> 

第一個是嵌入式數據庫,第二個是春季測試罐。

那麼,我會介紹我如何做測試和配置。

MyApplicationStandaloneConfiguration.java

@Configuration 
@Profile("local") 
@ComponentScan("cat.mypackages") 
public class MyApplicationStandaloneConfiguration { 

    @Bean 
    public DataSource myApplicationDataSource() throws NamingException { 

     DriverManagerDataSource dataSource = new DriverManagerDataSource(); 
     dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); 
     dataSource.setUrl("jdbc:hsqldb:mem:test"); 
     dataSource.setUsername("sa"); 
     dataSource.setPassword(""); 

     ResourceDatabasePopulator pop = new ResourceDatabasePopulator(); 
     pop.addScript(new ClassPathResource("sql/schema.sql")); 
     pop.addScript(new ClassPathResource("sql/one_table_inserts.sql")); 
     pop.addScript(new ClassPathResource("sql/another_table_inserts.sql")); 
     return dataSource; 
    } 

} 

注意,我這個註釋作爲@profile地方,這意味着我可以創造不同的環境中多個配置文件,例如,假設你想運行的集成測試針對您的開發/ qa/uat數據庫。

看到我正在加載schema.sql和其他一些sql腳本。這包含我創建表的模式以及我希望在我的測試用例中使用的插入。

然後很容易,創建測試用例這樣的:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = MyApplicationStandaloneConfiguration.class) 
@ActiveProfiles("local") 
public class MyDaoTestCase { 

    @Autowired 
    private MyDao dao; 

    @Test 
    public void testFindId() { 
     SomeDto dto = dao.findById(123); 
     assertNotNull(dto); 
     ... 
    } 

} 

希望它hepls!

相關問題