![](/img/trans.png)
[英]How can I use a variable for the “expected” attribute of junit @Test?
[英]Use variable in JUnit test
我想先保存VO並獲取其ID(主鍵),然后基於ID執行獲取和刪除操作。
我的密碼
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TransactionDAOImplTest {
TransactionDAOImpl daoImpl = new TransactionDAOImpl();
public long Id;
String transactionId = "1468597863";
String uniqueKey = "124587878";
// @Ignore
@Test
public void test1_savetransaction() {
transactionVO transactionVO = new TransactionVO();
transactionVO.setTransactionId(transactionId);
transactionVO.setUniqueKey(uniqueKey);
transactionVO.setCreationDate(Calendar.getInstance());
transactionVO vo = daoImpl.saveTransaction(transactionVO);
Id = vo.getId(); // Here Id is setting to some value like 775
assertEquals(transactionId, vo.getTransactionId());
}
// @Ignore
@Test
public void test2_findTransactionEvent() {
transactionVO vo = daoImpl.findTransaction(Id); // Here Id is reseting to 0 it should be 775, so not able to get
assertEquals(transactionId, vo.getTransactionId());
}
// @Ignore
@Test
public void test3_deletetransaction() {
int deletedCount = daoImpl.deleteTransactionById(Id); // Here also Id reseting to 0 it should be 775, so not able to delete
assertTrue(deletedCount > 0);
}
但是,當我設置Id並將其用於其他方法時,它會重置為0。
如何在所有JUnit測試方法中使用變量(例如,Id)?
將設置ID添加到BeforeClass,以便它將在所有方法中可用(必須是靜態的)
public static long Id;
@BeforeClass public static void onlyOnce() {
transactionVO transactionVO = new TransactionVO();
transactionVO.setTransactionId(transactionId);
transactionVO.setUniqueKey(uniqueKey);
transactionVO.setCreationDate(Calendar.getInstance());
transactionVO vo = daoImpl.saveTransaction(transactionVO);
Id = vo.getId(); // Here Id is setting to some value like 775
}
將id設置為靜態,因此每個jvm只能有一個副本。
static public long Id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.