postgresql 为什么约束在Testcontainers中不起作用?

6ojccjat  于 2023-03-08  发布在  PostgreSQL
关注(0)|答案(1)|浏览(171)

我正在尝试在我的spring Boot 应用程序中使用testcontainers。我也使用liquibase,我在那里有简单的代码:

create table calendar
(
    date date primary key,
    is_weekend boolean not null,
    is_pre_holiday boolean not null,
    check( not (is_weekend and is_pre_holiday) )
);

我想检查集成测试中的约束,如果我做错了,请帮助我
下面是我的休眠实体:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "calendar")
public class CalendarEntity {
    @Id
    LocalDate date;
    boolean isWeekend;
    boolean isPreHoliday;
}

application-integration-test.yaml

spring:
  jpa:
    hibernate:
      ddl-auto: validate
  datasource:
    url: jdbc:tc:postgresql://localhost/testDB
    username: user
    password: password
    driverClassName: org.testcontainers.jdbc.ContainerDatabaseDriver
  liquibase:
    change-log: classpath:db/changelog/changelog-master-test.yaml
    enabled: true

因此,从数据库获取日历的简单测试工作正常,但这并不正确,它没有引发异常或返回null:

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ActiveProfiles("integration-test")
public class CalendarRepositoryTest {

    @Autowired
    CalendarRepository calendarRepository;

    static PostgreSQLContainer<?> postgres= new PostgreSQLContainer<>("postgres:14")
            .withUsername("user")
            .withPassword("password")
            .withDatabaseName("test_db");

    @Test
    void dateCanNotBeWeekendAndPreHolidayTest() {
        CalendarEntity calendarEntity = new CalendarEntity(LocalDate.of(2000, 1, 1), true, true);

        CalendarEntity savedEntity = calendarRepository.save(calendarEntity);
        assertEquals(calendarEntity, savedEntity);
        //they are equal and test is passed, but it shouldn't
    }

附言
Spring Boot3.0.2
测试容器1.17.6
期待这样的结果:
错误:关系“calendar”的新行违反了检查约束条件“calendar_check”

nqwrtyyt

nqwrtyyt1#

感谢@Andrey B. Panfilov,我发现了我代码中的问题:我应该在测试中使用saveAndFlush
如果我们转到SimpleJpaRepository类,它是JpaRepository的实现,我们将发现:

@Transactional
    @Override
    public <S extends T> S save(S entity) {

        Assert.notNull(entity, "Entity must not be null");

        if (entityInformation.isNew(entity)) {
            em.persist(entity);
            return entity;
        } else {
            return em.merge(entity);
        }
    }

方法保存返回实体,该实体是给该方法的
测试中的saveAndFlush方法抛出异常,正如我所料:

2023-03-02T09:37:01.337+05:00 ERROR 6304 --- [    Test worker] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: new row for relation "calendar" violates check constraint "calendar_check"
  Подробности: Failing row contains (2000-01-01, t, t).

相关问题