Issue
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:
Solution
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())
Answered By - Olli