JUnit How to assertTrue/Equals on a Optional and a object

Viewed 2112

How do I use assert.equals to test between a Optional and a Object? After debugging it shows the same values but my test still fails to pass. Returning error: at org.springframework.test.util.AssertionErrors.assertTrue

My test class looks als following:

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")
@SpringBootTest
public class DishServiceTest {

    private static final String DISH_NAME = "Kaas";
    private static final String DISH_TYPE = "Voorgerecht";

    @Autowired
    private DishService dishService;

    @Test
    public void findById(){
        //execute
        Dish dish = createDish(DISH_NAME, DISH_TYPE);

        Long dishId = dish.getId();

        Optional<Dish> dish2 = dishService.findById(dishId);

        //verify
        assertNotNull(dish2);
        //assertEquals(Optional.of(dish2), dish);
        assertTrue("created a dish" ,Optional.of(dish2).equals(dish));
    }

    private Dish createDish(String dishName, String dishType) {
        Dish dish = new Dish();
        dish.setDishName(dishName);
        dish.setDishType(dishType);
        Dish retval = dishService.save(dish);
        return retval;
    }

My debugging results:

enter image description here

2 Answers

DishService.findById returns an Optional which is never null by contract; therefore, the assertNotNull in the test is a no-op. Assert the non-emptiness first with assertTrue(dish2.isPresent()) instead.

Then compare the content of the returned Optional object with:

assertEquals(dish, dish2.get())

Did you override equals() in class Dish? If not, Object.equals() is used, and that returns true only if an object is compared to itself. If you want an equals() function that returns true if the fields of two different Dish objects are all equal, you have to write it yourself.

Related