1. 程式人生 > >java用junit測試service層方法的工具類

java用junit測試service層方法的工具類

常規的寫法:

可以直接在junit測試類上寫註解

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:config/spring.xml"})
public class ScheWebServiceImplTest{

    @Test
    public void testDoCheckQatStatus() {
        System.out.println(123);
    }

}

但是每個都寫豈不是很low,AbstractJUnit4SpringContextTestsAbstractTransactionalJUnit4SpringContextTests,這兩個類已經用@RunWith修飾了,所以我們來做一個測試的基類:

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

@ContextConfiguration(locations = {"classpath:config/spring.xml"})
public class BaseJunit extends AbstractJUnit4SpringContextTests{

}

這樣以後再做junit測試類的時候,只需讓測試類繼承基類就可以了。

基類繼承AbstractTransactionalJUnit4SpringTests:執行測試後不會改變資料庫的內容,也就是說你測試的操作都會回滾回去

繼承AbstractJUnit4SpringContextTests :則不會回滾,操作會直接影響資料庫