一、JUnit4使用Java5中的註解(annotation)
@Before:初始化方法 對於每個測試方法都要執行一次(注意與BeforeClass區別,後者是對於全部方法執行一次)
@After:釋放資源 對於每個測試方法都要執行一次(注意與AfterClass區別,後者是對於全部方法執行一次)
@Test:測試方法,在這裏能夠測試指望異常和超時時間
@Test(expected=ArithmeticException.class)檢查被測方法是否拋出ArithmeticException異常
@Ignore:忽略的測試方法
@BeforeClass:針對全部測試,只執行一次,且必須爲static void
@AfterClass:針對全部測試,只執行一次,且必須爲static void
一個JUnit4的單元測試用例執行順序爲:
@BeforeClass -> @Before -> @Test -> @After -> @AfterClass;
每個測試方法的調用順序爲:單元測試
@Before -> @Test -> @After;測試
二、執行順序
隨機執行
@FixMethodOrder(MethodSorters.DEFAULT)
public class TestOrder
按testcase名稱字符串順序執行
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestOrderthis
三、代碼注入Mock
JMokit中的@Mocked與@Injectable區別資源
public class CommonDaoTest {
@Mock
private MongoTemplate mongoTemplate; //注入mongdb mock類,不訪問庫
@InjectMocks //注入的目標類,要實現的test類
private CommonDao commonDao;文檔
@Before
public void setUp() {
MockitoAnnotations.initMocks(this); //此處必定要記得加上,不然出錯
}字符串
@Test
public void dropCollectionName() {
doNothing().when(mongoTemplate).dropCollection("116");
commonDao.dropCollectionName("116"); //CommonDao實現了刪除文檔的功能
}
}
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>1.23</version>
<scope>test</scope>
</dependency>get
四、各類mock示例
when(systemConfigurationService.getConfiguration(eq(String.class), anyString())).thenReturn("(\\d+\\.*\\d*)");
when(objService.getKnowledgePointList(anyList())).thenReturn(objectiveKnowledges);
when(mongoTemplate.updateFirst(any(Query.class), any(Update.class), anyString())).thenReturn(mock(WriteResult.class));it
when(mongoTemplate.collectionExists("111")).thenReturn(false);io
when(configRepository.findByType(anyString())).thenReturn(mock(Config.class));table