2013-03-19 125 views
1

我的應用程序使用JPA(1.2),Spring(3.1.2),Spring Data(1.1.0)和Hibernate(4.1.7)。JPA測試框架

我們需要編寫用於測試Entity和Repository的Junit測試用例,但是我們無法找到適用於測試JPA所有場景的Junit和framwork的正確示例。

請讓我們知道爲Junit編寫JPA存儲庫和實體的框架是否正確。

+2

JPA1.2不存在。 1.0? 2.0? 2.1? – DataNucleus 2013-03-19 12:53:09

回答

0

我會推薦使用Spring Test框架,它使開發人員能夠用測試引導依賴注入容器。然後,您可以將您的存儲庫自動裝入測試。

這裏是我已經使用了框架,摘錄測試:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={"classpath:META-INF/spring/test-context.xml"}) 
@TransactionConfiguration(defaultRollback=false) 
public class CommentRepositoryTest { 

    @Autowired 
    private CommentRepository repository; 

    @Autowired 
    PostRepository postRepository; 

    @Test 
    public void findOneTest(){ 
     Comment comment= repository.findOne(1); 
     assertNotNull(comment); 
     assertEquals("John Doe", comment.getAuthor()); 
    } 

} 

通知的@ContextConfiguration指向的Spring Bean配置文件如何。那是依賴注入容器被引導。 @Autowired註釋正在注入我的存儲庫進行測試。 @TransactionConfiguration告訴Spring不要回滾測試,以便可以針對沙箱數據庫運行單元測試,這可能會暴露回滾功能隱藏的問題。

我有一個項目,演示GitHub上的配置。

我還創建了一個視頻教程,演示如何configure jUnit tests with Spring Test

我也有一個test使用@Transactional註釋的例子。

+0

每個測試函數都有自己的事務,所以我需要在一個函數中測試所有的東西,但這不正確。如果你有任何例子,請給我提供鏈接 – 2013-03-19 09:07:20

+0

@RanuJain所以你說的測試將是'@ Transactional',也許會持續多個實體? – 2013-03-19 09:08:23

+0

是的......我們已經用SpringJunit編寫了Junit類,但它沒有給出正確的結果。有些地方我們有其他實體的依賴關係,然後在測試時,一切正常,但實際上當我們試圖保存它的拋出錯誤時。因爲在測試中它實際上並沒有因爲@Transaction而在數據庫中插入數據。 – 2013-03-19 09:12:55