[英]How to get the second from LocalDateTime objects in a method with return type LocalDateTime?
我從兩個 LocalDateTime 對象中獲取秒數時遇到問題。
// a timestammp for the time when the connection was established
public LocalDateTime establish() {
startTime = LocalDateTime.now();
connectionEstablished = true;
return startTime;
}
// timestamp for the time when the connection was disconnected
public LocalDateTime disconnect() {
endTime = LocalDateTime.now();
connectionDisconnected = true;
return endTime;
}
// get the second when the connection was established
public LocalDateTime getStartTime() {
}
// get the seconds when the connection was disconnected
public LocalDateTime getEndTime() {
}
在 getStartTime() 和 getEndTime 方法中,返回類型必須來自 LocalDateTime。 我嘗試了不同的方法,例如使用 Duration.between,使用 Temporal 作為返回類型但它不起作用,因為 Junit 測試給出返回類型必須為 LocalDateTime 的錯誤。
這是 Junit 測試:
@Test
void test() throws InterruptedException {
cdr.establish();
System.out.println(cdr.toString());
assertTrue(cdr.toString().matches("calling: \\+44 44\\/725 8912, called: \\+1 982\\/543 1201, start: " + TIMESTAMP_PATTERN + ", end: still established"));
assertEquals(0.0, Duration.between(cdr.getStartTime(), LocalDateTime.now()).getSeconds(), 0.1);
assertNull(cdr.getEndTime());
Thread.sleep(1000);
cdr.establish();
// it fails here
assertEquals(1.0, Duration.between(cdr.getStartTime(), LocalDateTime.now()).getSeconds(), 0.1);
Thread.sleep(1000);
cdr.disconnect();
System.out.println(cdr.toString());
assertTrue(cdr.toString().matches("calling: \\+44 44\\/725 8912, called: \\+1 982\\/543 1201, start: " + TIMESTAMP_PATTERN + ", end: " + TIMESTAMP_PATTERN));
assertEquals(2.0, Duration.between(cdr.getStartTime(), cdr.getEndTime()).getSeconds(), 0.1);
Thread.sleep(1000);
cdr.disconnect();
assertEquals(2.0, Duration.between(cdr.getStartTime(), cdr.getEndTime()).getSeconds(), 0.1);
}
任何幫助表示贊賞。 謝謝 !
您正在正確獲取兩個本地日期時間之間的秒數。 測試的目的是確保當第二次調用establish
時(即當連接已經建立時), startTime
不會被重置。 測試基本上說:
一秒后,再次建立連接,開始時間應該是現在之前的一秒(而不是正好現在)。
您可能應該更改establish
方法:
public LocalDateTime establish() {
if (!connectionEstablished) { // add this check
startTime = LocalDateTime.now();
}
connectionEstablished = true;
return startTime;
}
而不是assertEquals
嘗試assertTrue
。
這是一個例子:
assertTrue(Duration.between(cdr.getStartTime(), LocalDateTime.now()).getSeconds() >= 1L);
請注意, getSeconds
返回一個long
值,而1.0
不是long
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.