我想先保存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)?
答案 0 :(得分:3)
将设置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
}
答案 1 :(得分:2)
将id设为静态,因此每个jvm只有一个副本。
static public long Id;