有時候咱們須要按照順序執行咱們的單元測試方法,如在測試Dao層的時候要按照測試插入方法、查詢方法、更新方法、刪除方法的順序測試。java
package com.tiamaes.dao; import static org.junit.Assert.fail; import java.util.Date; import static org.junit.Assert.*; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.tiamaes.bean.GjdsBusSite; import com.tiamaes.bean.dao.GjdsBusSiteDao; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") @FixMethodOrder(MethodSorters.DEFAULT) public class GjdsBusSiteDaoTest { private GjdsBusSite bean = new GjdsBusSite(); //private String id = UUID.randomUUID().toString(); private String id = "57706cd4-244e-4101-a317-ee34347c4168"; @Autowired private GjdsBusSiteDao gjdsBusSiteDao; @Before public void init(){ System.out.println(id); bean.setId(id); bean.setBusNo("125412"); bean.setLat(123.1111); bean.setLng(24.1111); bean.setSiteTime(new Date()); bean.setLineNo("B1"); } @Test public void testDao(){ assertNotNull(this.gjdsBusSiteDao); } @Test public void testSave() { this.gjdsBusSiteDao.save(bean); } @Test public void testGet() { GjdsBusSite entity = this.gjdsBusSiteDao.get(id); assertNotNull(entity); assertNotNull(id,entity.getId()); } @Test @Ignore public void testUpdate() { fail("Not yet implemented"); } @Test @Ignore public void testRemove() { //fail("Not yet implemented"); this.gjdsBusSiteDao.remove(id); GjdsBusSite e = this.gjdsBusSiteDao.get(id); assertNull(e); } }
由於用到了Spring因此須要將Runner指定爲SpringJUnit4ClassRunner並使用@ContextConfiguration指定配置文件。spring
@Before用來初始化Bean,在每一個方法執行時都會執行一次app
@Ignore指定忽略此測試方法dom
@FixMethodOrder用來指定方法執行順序,傳入一個MethodSorters單元測試
DEFAULT會按照方法的順序執行測試
NAME_ASCENDING:對方法名升序排序,而後按照排序後的順序執行this