gpt4 book ai didi

java - 将 PowerMockRunner 与 LocalDate 类一起使用来模拟今天的日期

转载 作者:行者123 更新时间:2023-11-29 06:49:47 26 4
gpt4 key购买 nike

考虑如下使用 PowerMockRunnerDateUtilTest 类:

import com.reporting.utils.DateUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.time.LocalDate;
import java.util.Date;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;

@PrepareForTest(DateUtil.class)
@RunWith(PowerMockRunner.class)
public class DateUtilTest {


@Test
public void getPreviousWorkingDayAsDate_whenMonday() {
//given
LocalDate date = LocalDate.of(2017, 10, 16);
LocalDate expected = LocalDate.of(2017, 10, 13);

mockStatic(LocalDate.class);
when(LocalDate.now()).thenReturn(date);

//when
Date previousWorkingDay = DateUtil.getPreviousWorkingDayAsDate();


//then
assertEquals(DateUtil.getDateFromLocalDate(expected), previousWorkingDay);
}

@Test
public void getPreviousWorkingDayAsDate2_whenMonday() {
//given
LocalDate date = LocalDate.of(2017, 10, 16);


mockStatic(LocalDate.class);
when(LocalDate.now()).thenReturn(date);

//when
Date previousWorkingDay = DateUtil.getPreviousWorkingDayAsDate();
LocalDate expected = LocalDate.of(2017, 10, 13);


//then
assertEquals(DateUtil.getDateFromLocalDate(expected), previousWorkingDay);
}

}

我想了解为什么 @Test ==> getPreviousWorkingDayAsDate2_whenMonday 在我移动 expected LocalDate 初始化时失败在模拟 LocalDate.class 之后?

此外,是否可以改进此测试?

最佳答案

此外,是否可以改进此测试?

是 - 重构 DateUtil 以能够使用特定的 Clock。例如:

public class DateUtil {
private static Clock clock = Clock.systemDefaultZone();

public static setClock(Clock clock) {
assertNotProduction(); // optionally check for an environment/system variable to throw exception if used in production
DateUtil.clock = clock;
}

public static Date getPreviousWorkingDayAsDate() {
LocalDate today = LocalDate.now(clock); // use clock
...
return ...;
}
}

然后单元测试不需要任何模拟。例如:

@Test
public void getPreviousWorkingDayAsDate_whenMonday() {
//given
LocalDate monday = LocalDate.of(2017, 10, 16);
Clock clock = Clock.fixed(monday.atStartOfDay(ZoneId.systemDefault()).toInstant(), ZoneId.systemDefault());
DateUtil.setClock(clock);

LocalDate lastFriday = LocalDate.of(2017, 10, 13);

//when
Date previousWorkingDay = DateUtil.getPreviousWorkingDayAsDate();

//then
assertEquals(DateUtil.getDateFromLocalDate(lastFriday), previousWorkingDay);
}

@After
public void resetClock() {
DateUtil.setClock(Clock.systemDefaultZone());
}

关于java - 将 PowerMockRunner 与 LocalDate 类一起使用来模拟今天的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52611458/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com