0

I need to write test case using junit 5 and assertThat to check for null value.

I have written as below. However, this is giving error with respect to mismatch datatype.

enter image description here

    @Test
    void shouldReturnNull() {
        assertThat(OffsetDateTimeConverter.toOffsetDateTime(null), nullValue(OffsetDateTime.class));
    }

Tried this as well. However again same error.

    @Test
    void shouldReturnNull() {
        assertThat(OffsetDateTimeConverter.toOffsetDateTime(null), is(nullValue(OffsetDateTime.class)));
    }

Any example/suggestion how to use nullValue(T type) to fix this issue?

I need to write testcase where I can validate if java.sql.Date is correctly converted into java.time.OffsetDateTime using my Converter class. Hence, I have written as below.

@Test
    void toOffsetDateTime() {
        Date date = new Date(System.currentTimeMillis());
        assertThat(date.toLocalDate()).isEqualTo(OffsetDateTimeConverter.toOffsetDateTime(date).toLocalDate());
    }

Above test case is working fine.

I want to know if this is a right approach as I am converting both actual and expected value to local date to compare them ?

user2800089
  • 2,015
  • 6
  • 26
  • 47
  • Can you try like `assertThat(cheese, is(nullValue(Cheese.class))`? Ref: http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/core/IsNull.html#nullValue(java.lang.Class) – Liquidpie Jul 14 '20 at 07:02
  • @Liquidpie Tried suggested approach, same error. Updated question as well. – user2800089 Jul 14 '20 at 07:20
  • what's your `OffsetDateTimeConverter.toOffsetDateTime()` method look like? – Liquidpie Jul 14 '20 at 07:40
  • @Liquidpie return Optional.ofNullable(date).map(d-> OffsetDateTime.of(d.toLocalDate(), LocalTime.NOON, ZoneOffset.UTC)).orElse(null); – user2800089 Jul 14 '20 at 07:42

1 Answers1

0

Seems to me you're using wrong assertThat method.

You're using assertThat method from assertj where you should be using hamcrest one. For ex: org.hamcrest.MatcherAssert.assertThat

Liquidpie
  • 1,589
  • 2
  • 22
  • 32
  • Yeah, you are right. wrong import was the issue.Could you also let me know your thoughts on my second question. I want to know is this a right practice to alter actual and expected result to match value? – user2800089 Jul 14 '20 at 09:07
  • 1
    It would be better if your expected type is same as the return type of method under test (as `OffsetDateTime`). But, sometimes it happens that there's no easy way to come up with as the same type, it's fine to use a common type for comparison. It's expected to give same result – Liquidpie Jul 14 '20 at 09:13