簡體   English   中英

JUnit測試事務方法

[英]JUnit testing transactional methods

我是JUnit的新手並嘗試測試使用JPA DAO的spring Web服務。 我需要測試類似於下面的服務方法。

服務方法使用@Transactional(propagation=Propagation.REQUIRED)注釋, ServiceObjectRepository.update()方法調用本機sql查詢來更新數據庫。

@Transactional(propagation=Propagation.REQUIRED)    
public void serviceMethod(){
        //Read DB for ServiceObject to update
        //Call  ServiceObjectRepository.update() method to update DB
}

ServiceObjectRepository

public interface ServiceObjectRepository  extends JpaRepository<ServiceObject, Integer> {

    @Query(value ="UPDATE serviceobjcet AS c SET c.objectstatus= :os WHERE c.objid = :oi", nativeQuery = true)
    public Integer update(@Param("os")short objStatus,@Param("oi")int objId);    
}

識別TestClass

@TransactionConfiguration(defaultRollback=true)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
        locations = "classpath:service-test.xml")
@Transactional
public class ServiceHandlerTest {

    @Test
    public void testServiceMethod() {

        //Create ServiceObject and save to DB
        //Call serviceMethod()
        //Read DB for updatedServiceObject

        assertEquals("Test: Object should be in updated state", new Short(3), updatedServiceObject.getObjectstatus(), 0);

   }
}

我的測試運行並回滾數據庫事務。 但問題是當我在調用updatedServiceObject之后讀取serviceMethod它不會返回更新的對象。 所以我的測試在assertEquals失敗並出現NullPointerException。 有沒有想過克服這個問題?

最后我想出了一個解決方案,而不是在測試方法中創建ServiceObject並保存到DB,我在測試方法之前完成了它,並在事務之后刪除了創建的對象。 所以我的測試類看起來像,

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:service-test.xml")

public class ServiceHandlerTest {

    @Before
    public void setup() {
        //Create ServiceObject and save to DB
    }


    @Test
    public void testServiceMethod() {
        //Call serviceMethod()
        //Read DB for updatedServiceObject

        assertEquals("Test: Object should be in updated state", new Short(3), updatedServiceObject.getObjectstatus(), 0);
    }

    @After
    public void teardown() {
        //Delete created ServiceObject from DB
    }
}

我發現測試方法或測試類在這種情況下不必是事務性的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM