1/17/2011

How to test job in Quartz

之前工作排程都是使用Java Quartz來設計,但確沒有好好想過要如何測試 (有時候承認不夠好或許就是進步泉源),真的很不應該!

工作排程環境要模擬也確實滿複雜,但可利用Mock觀念 讓我們追縱瞭解物件內部流程,確保物件活動如預期中運作。

mock objects

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A computer programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts. Mock objects help you design and test the interactions between the objects in your programs.

利用著名 jMock 發現存在一些限制,僅能Mock介面(interface.class)。

因此找了另一套Mockito,使用過發現真的滿好用! Mockito應該花一點時候來研究

Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with clean & simple API. Mockito doesn't give you hangover because the tests are very readable and they produce clean verification errors. Read more about features & motivations.

如何測試Quartz工作排程

[code lang="java"] import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @Test public void testJob() throws JobExecutionException, ParseException { ... SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); JobExecutionContext ctx = mock(JobExecutionContext.class); JobDetail detail = mock(JobDetail.class); JobDataMap map = new JobDataMap(); map.put("query_date", sdf.parse("2011/01/14")); when(detail.getJobDataMap()).thenReturn(map); when(ctx.getJobDetail()).thenReturn(detail); new TransactionJob().execute(ctx); ... } [/code]

產生三個Mock物件{JobExecutionContext, JobDetail, JobDataMap } 針對Job所使用參數,將查詢天數放至JobDataMap中。設定程式When呼叫時回傳Mock 物件,JobExecutionContext 參數帶入執行。

利用Mock設計、重覆測試能夠有效提升程式品質,也不需要為了模擬Job環境搞死自己。

4 comments:

  1. 這文挺讚~不過你的code失效啦

    ReplyDelete
  2. Bài viết của Bạn rất hay, thank bạn đã chia sẻ.
    Thông tin thêm : Gia công đá thạch anh

    ReplyDelete
  3. Thông tin của admin cũng hữu ích, cám ơn bạn vừa chia sẻ.
    Xem thêm tại website: Vòng thạch anh

    ReplyDelete
  4. Bài post của tác giả thật cần thiết, thank chị đã share.
    Page hữu ích : Tỳ hưu

    ReplyDelete