我有以下应用程序代码。
应用代码
public static long advanceByMax1HourWithoutOverflow(long currentTimeMillis) {
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = Instant.ofEpochMilli(currentTimeMillis).atZone(zoneId);
// 0-23
int hour = zonedDateTime.getHour();
if (hour < 23) {
zonedDateTime = zonedDateTime.plusHours(1);
return zonedDateTime.toInstant().toEpochMilli();
}
// 0-59
int minute = zonedDateTime.getMinute();
if (minute < 59) {
zonedDateTime = zonedDateTime.plusMinutes(1);
return zonedDateTime.toInstant().toEpochMilli();
}
return currentTimeMillis;
}
我用以下内容为它编写了一个单元测试。
单元测试代码
@Test
public void advanceByMax1HourWithoutOverflow() {
/*
27 October 2018
1540648800000 -> 1540652400000
22:00 -> 23:00
*/
long currentTimeMillis = 1540648800000L;
long expected = 1540652400000L;
long output = Utils.advanceByMax1HourWithoutOverflow(currentTimeMillis);
assertEquals(expected, output);
我收到以下错误
org.threeten.bp.zone.ZoneRulesException: No time-zone data files registered
我试图通过使用来修复它
单元测试代码
@Test
public void advanceByMax1HourWithoutOverflow() {
Context context = mock(Context.class);
AndroidThreeTen.init(context);
/*
27 October 2018
1540648800000 -> 1540652400000
22:00 -> 23:00
*/
long currentTimeMillis = 1540648800000L;
long expected = 1540652400000L;
long output = Utils.advanceByMax1HourWithoutOverflow(currentTimeMillis);
assertEquals(expected, output);
我越来越
java.lang.ExceptionInInitializerError
at org.threeten.bp.ZoneRegion.ofId(ZoneRegion.java:143)
at org.threeten.bp.ZoneId.of(ZoneId.java:358)
at org.threeten.bp.ZoneId.of(ZoneId.java:286)
at org.threeten.bp.ZoneId.systemDefault(ZoneId.java:245)
有什么方法可以通过单元测试,而无需更改当前应用程序的方法签名?我想只保留我当前的应用程序方法签名而不做任何修改。
long advanceByMax1HourWithoutOverflow(long currentTimeMillis)
请注意,我用于单元测试的 gradle 是
implementation 'com.jakewharton.threetenabp:threetenabp:1.1.1'
testImplementation 'junit:junit:4.12'
testImplementation 'org.mockito:mockito-core:2.19.0'