在多个Java方法中使用时,全局时间戳记变量返回空值

问题描述

我遇到了一个奇怪的情况,即本地时间戳变量可以正常工作,并在测试方法A中返回ArrayList的正确第一个值。现在,我想在测试方法B中使用该变量,因此我将变量转换为在类级别声明的全局变量。奇怪的是,从ArrayList id测试方法B返回的第一个值是null。显然,问题在于第二个方法无法正确读取变量。第一种方法将其读取确定。我不确定我做错了什么。这是我尝试过的:

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的即时变量,但是您设置的变量在您的测试方法中是本地的。它仅存在于该测试的范围内,不会更改其他测试可以达到的。

即使现在也许有所不同,但不确定测试是否按照您希望的顺序执行。 如果您希望在每次测试前立即设置该值,请添加以下内容:

@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
}

这样,您在两个测试中都具有该元素,但是测试彼此之间并不相互依赖。