I’m trying to write some unit tests for a many to many relationship with an association table with a couple extra columns. Realistically if I try to delete an ingredient and then flush the db it should throw an exception bc of the foreign key constraint. The test IS NOT THROWING. When I try to do this manually in my Postgres db, it does fail. My tests cases are using H2. Uncertain if that might be why. The bizarre thing is that even though it’s not throwing, I checker the count after delete is called and it doesn’t seem like anything is deleted either? Hibernate seems to be silently ignoring it.
Main question: why is this there no exception thrown in the unit test?
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Table(uniqueConstraints = @UniqueConstraint(columnNames = { "recipe_id", "ingredient_id" }))
public class RecipeIngredient {
public static enum Unit {
KILOGRAM, GRAM, MILLIGRAM, OUNCE, POUND, MILLILITER, LITER,
TEASPOON, TABLESPOON, FLUID_OUNCE, CUP, PINT, QUART, GALLON,
PIECE, SLICE, CLOVE, STICK, CAN, UNSPECIFIED,
BOTTLE, PACK, DASH, PINCH, DROP;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long recipeIngredientId;
@ToString.Exclude
@ManyToOne(optional = false)
@JoinColumn(
name = "recipe_id",
referencedColumnName = "recipeId",
nullable = false,
foreignKey = @ForeignKey(name = "recipe_id_fkey")
)
private Recipe recipe;
@ToString.Exclude
@ManyToOne(optional = false, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinColumn(
name = "ingredient_id",
referencedColumnName = "ingredientId",
nullable = false,
foreignKey = @ForeignKey(name = "ingredient_id_fkey")
)
private Ingredient ingredient;
@Enumerated(EnumType.STRING)
private Unit unit;
@NotNull
@Positive
@Column(nullable = false)
private Double quantity;
}
@Test
public void shouldFailToDeleteIngredient(){
Recipe recipe = getRecipe();
testEntityManager.persist(recipe);
testEntityManager.flush();
assertThrows(PersistenceException.class, () -> {
ingredientRepository.deleteAll();
ingredientRepository.flush();
testEntityManager.flush(); // Forces DB constraint to be evaluated
});
}
- Tried deleting manually in the postgres db, it does error out there.
- Checking the count instead of trying to assert that an exception returns doesn’t show any evidence of any records being deleted by ingredientRepository.deletAll();
- I was expecting this test to assert that an exception was in fact thrown.
- there are foreign key constraints on my posgres table when I run the server itself- so i’d assume it’d be the same for H2? Uncertain.