java - 全局时间戳变量在多个 java 方法中使用时返回空值
问题描述
我遇到了一个奇怪的情况,本地时间戳变量完美地工作并在测试方法 A 中返回 ArrayList 的正确第一个值。现在,我想在测试方法 B 中使用该变量,所以我将变量转换为全局变量,在类级别声明。奇怪的是,ArrayList id 测试方法 B 返回的第一个值是 null,显然,问题在于第二种方法没有正确读取变量。第一种方法读取它OK。我不确定我做错了什么。这是我尝试过的:
private static Timestamp s; //variable declared globally
private static final TestDao TEST_DAO = new TestDao();
// 1st test method
@Test
public void testById() {
List<TestEntity> tests = TEST_DAO.findById("");
List<Timestamp> myDate = new ArrayList<>();
for (TestEntity test: tests) {
myDate.add(test.getDateColumn());//A list element added to the array
}
s = myDate.get(0); //Gets the first element from the list
System.out.println("The first element is " + s); //The variable s successfully returns the first element of the array
//2nd test method
@Test
public void verifyMe() {
LocalDateTime dateTime = LocalDateTime.now().plus(Duration.of(1, ChronoUnit.MINUTES));
Date nowPlusOneeMinutes = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("The first element is " + s); //s returns a null value here even though it's declared as private static as class level
}
解决方案
首先Java没有“全局变量”的概念
private static Timestamp s; //variable declared globally
private static final TestDao TEST_DAO = new TestDao();
// 1st test method
@Test
public void testById() {
List<TestEntity> tests = TEST_DAO.findById("");
List<Timestamp> myDate = new ArrayList<>();
for (TestEntity test: tests) {
myDate.add(test.getDateColumn());//A list element added to the array
}
Timestamp s = myDate.get(0); //Gets the first element from the list
System.out.println("The first element is " + s); //The variable s successfully returns the first element of the array
}
是的,您确实有一个名为 s 的即时变量,但您设置的变量是您的测试方法的本地变量。它只存在于该测试的范围内,不会改变其他测试可以达到的 s。
即使,也许现在情况有所不同,但不确定测试是否按照您希望的顺序执行。如果您希望在每次测试之前设置该值,请添加:
@Before
public void init() {
List<TestEntity> tests = TEST_DAO.findById("");
List<Timestamp> myDate = new ArrayList<>();
for (TestEntity test: tests) {
myDate.add(test.getDateColumn());//A list element added to the array
}
s = myDate.get(0); // this will actually set the value of the s on instance level
}
这样,您在两个测试中都有元素,但测试并不相互依赖。
推荐阅读
- office-js - Microsoft Teams 中未显示管理员管理的 Office Web 插件
- php - 事务在 CodeIgniter 中无法正常工作
- php - 通过 PHPMailer 发送 SMTP 电子邮件突然开始失败
- netlogo - 如何在一系列值中随机设置乌龟变量?
- swift - 在将 firebase pod 更新到最新版本时收到“找不到框架 MeasurementNanoPB”错误
- python - Flask 库上的 ValueError
- parsing - How to parse multiple for loops and generate new classes
- scala - getting file information without uploading using scala
- arrays - 在构建和阵列时在bash中修改IFS
- javascript - Can I use JSTL operations as statements in javascript?