简体   繁体   中英

How to give a timestamp value as an argument in java?

I am learning about unit testing and I want to write a test method for a method which converts a string to timestamp. The return type of the method is Timestamp and the parameter is String. I know that the function returns the correct value when I debug it. For example if the input is "07.10.2018 08:45:00" , then the value returned should be 2018-10-07 08:45:00.0 (of type timestamp). How do I pass this value to assertEquals in test method? What is the correct format of passing a Timestamp value to a function?

Or is there any other way for testing it?

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 );
    }

You can check with Time api usage without string to timestamp convert operation.

Your date string is 07.10.2018 08:45:00 .

If you convert this string to TimeStamp value , use this code ;

final Timestamp timestamp = 
        Timestamp.valueOf(LocalDateTime.of(LocalDate.of(2018, 10, 7), LocalTime.of(8, 45, 0)));

And then compare two Timestamp which one is coming from your convertStringToTimestamp method and other one is timeStamp with my provided code's.

So final code should be like this ;

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);

I would like to give you a very short example on OffsetDatetime which should work similarly.

Important is, that for Unit tests you define your expected outcome pretty well. So you tell the test what you expect and compare it then with the desired outcome and behaviour.

Please have a short look:

@Test
public void shouldReturnTimestamp() throws Exception {
    //Given
    final String toParse = "2018-10-05T14:49:27.000+02:00";
    final OffsetDateTime expected = OffsetDateTime.of(2018, 10, 05, 14, 49, 27, 0, ZoneOffset.ofHours(2));
    //When
    final OffsetDateTime actual = new OffsetDateTimeConverter().apply(toParse);
    //Then
    assertThat(actual).isEqualTo(expected);
}

class OffsetDateTimeConverter implements Function<String, OffsetDateTime> {

    @Override
    public OffsetDateTime apply(final String s) {
        return OffsetDateTime.parse(s);
    }
}

Does it somehow help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM