Search code examples
javaandroidunit-testingtestingguava

Best practice to verify Optional using hamcrest


This test is not working

assertThat(bundle.getMyObj(), equalTo(Optional.absent()));

At the beginning I just use a common object. (Didn't use optional<> yet)

private MyObj myObj;

The test will look like this

assertThat(myBundle.getMyObj(), nullValue());

The I change myObj to

private Optional<MyObj> myObj = Optional.absent();

Then I changed my test to

assertThat(bundle.getTracking(), equalTo(Optional.absent()));

Then I got an error

java.lang.AssertionError: 
Expected: <Optional.absent()>
     but: was <Optional.of(com.my.package.MyObj@2a9627bc)>
Expected :<Optional.absent()>

Actual   :<Optional.of(com.my.package.MyObj@2a9627bc)>

I also try this code below but got compile error

assertThat(myBundle.getMyObj(), equalTo(Optional.of(MyObj)));

Solution

  • This message:

    java.lang.AssertionError: 
    Expected: <Optional.absent()>
    but: was <Optional.of(com.my.package.MyObj@2a9627bc)>
    Expected :<Optional.absent()>
    Actual   :<Optional.of(com.my.package.MyObj@2a9627bc)>
    

    Says that your Optional object is not empty. It seems that bundle.getTracking() is returning not empty optional.

    Also, if you want check if optional is empty or not in your test, I recommend you to use method isPresent().

    Instead of assertThat(bundle.getTracking(), equalTo(Optional.absent())) just use assertTrue(bundle.getTracking().isPresent())