猿问

如何在java中给出时间戳值作为参数?

我正在学习单元测试,我想为将字符串转换为时间戳的方法编写测试方法。该方法的返回类型为Timestamp,参数为String。我知道该函数在调试时返回正确的值。例如,如果输入是"07.10.2018 08:45:00",则返回的值应该是2018-10-07 08:45:00.0(时间戳类型)。如何在测试方法中将此值传递给 assertEquals?将时间戳值传递给函数的正确格式是什么?


或者有没有其他方法可以测试?


public void test() {

        IDManager  test = new IDManager();


        Timestamp output = test.convertStringToTimestamp("07.10.2018 08:45:00");

        //assertEquals(2018-10-07 08:45:00.0,output );

    }


qq_花开花谢_0
浏览 207回答 2
2回答

梦里花落0921

你可以用时间API的使用没有检查string到timestamp转换操作。您的日期字符串是07.10.2018 08:45:00.如果将此字符串转换为TimeStamp值,请使用此代码;final Timestamp timestamp =         Timestamp.valueOf(LocalDateTime.of(LocalDate.of(2018, 10, 7), LocalTime.of(8, 45, 0)));然后比较两个时间戳,其中一个来自您的convertStringToTimestamp方法,另一个来自timeStamp我提供的代码。所以最终的代码应该是这样的;IDManager  test = new IDManager();Timestamp output = test.convertStringToTimestamp("07.10.2018 08:45:00");final Timestamp timestamp =        Timestamp.valueOf(LocalDateTime.of(LocalDate.of(2018, 10, 7), LocalTime.of(8, 45, 0)));Assert.assertEquals("TimeStamps should match!", timestamp, output);

九州编程

我想给你一个关于 OffsetDatetime 的非常简短的例子,它应该类似地工作。重要的是,对于单元测试,您可以很好地定义预期结果。所以你告诉测试你期望什么,然后将它与期望的结果和行为进行比较。请看一下:@Testpublic void shouldReturnTimestamp() throws Exception {&nbsp; &nbsp; //Given&nbsp; &nbsp; final String toParse = "2018-10-05T14:49:27.000+02:00";&nbsp; &nbsp; final OffsetDateTime expected = OffsetDateTime.of(2018, 10, 05, 14, 49, 27, 0, ZoneOffset.ofHours(2));&nbsp; &nbsp; //When&nbsp; &nbsp; final OffsetDateTime actual = new OffsetDateTimeConverter().apply(toParse);&nbsp; &nbsp; //Then&nbsp; &nbsp; assertThat(actual).isEqualTo(expected);}class OffsetDateTimeConverter implements Function<String, OffsetDateTime> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public OffsetDateTime apply(final String s) {&nbsp; &nbsp; &nbsp; &nbsp; return OffsetDateTime.parse(s);&nbsp; &nbsp; }}它有什么帮助吗?
随时随地看视频慕课网APP

相关分类

Java
我要回答