Home > Mobile >  Testing JdbcSQLIntegrityConstraintViolationException on repository layer
Testing JdbcSQLIntegrityConstraintViolationException on repository layer

Time:09-23

I have the following Entity:

@Data
@Entity
@Table(name = DbConstants.TBL_REVIEWS, schema = DbConstants.SCHEMA_PUBLIC)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Review {

    @Id
    @SequenceGenerator(
            name = DbConstants.SEQ_REVIEWS_ID,
            sequenceName = DbConstants.SEQ_REVIEWS_ID,
            allocationSize = DbConstants.ALLOCATION_SIZE
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = DbConstants.SEQ_REVIEWS_ID
    )
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "author_id", nullable = false)
    private Long authorId;

    @Column(name = "comment")
    private String comment;

    @Column(name = "rating")
    private Integer rating;

    @Column(name = "created_at", nullable = false)
    private LocalDateTime createdAt;
}

and the following test:


    @Test
    void testCreateRecipe_FailNameIsBlank() {
        Review review = new Review();
        review.setComment("Comment New");
        review.setRating(4);
        review.setCreatedAt(LocalDateTime.now());
            assertThrows(
                    ConstraintViolationException.class,
                    () -> {
                        reviewRepository.save(review);}
            );
    }

I want to test if exception will be thrown when no authorId is provided.

Question 1 - should it be tested in the repository layer tests. Question 2 - I'm getting :


org.opentest4j.AssertionFailedError: Expected org.hibernate.exception.ConstraintViolationException to be thrown, but nothing was thrown.
...
Suppressed: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

Note - tried changing the exception which I try assert is thrown to org.opentest4j.AssertionFailedError: Expected org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException to be thrown, but nothing was thrown. but didn't work out also.

Any help is well welcomed.

CodePudding user response:

Q1: You can test it anywhere you like I guess.

Q2: Use saveAndFlush to trigger the exception.

  • Related