我正在使用Spring Boot(2.1.4)并尝试编写一个简单的单元测试以删除 一个实体。实体(为简洁起见,省略了某些部分):
@Entity
@Table(name = "my_table")
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
@Getter
@Type(type="uuid-char")
@Column(name = "attribute_id", unique = true, nullable = false)
protected UUID attributeId;
@Version
protected Date version;
@Getter
@Column(unique = true, nullable = false)
protected String value;
}
该实体有一个简单的存储库:
public interface MyEntityRepository extends PagingAndSortingRepository<MyEntity, Long> {
Optional<MyEntity> findByMyId(UUID id);
}
单元测试使用内存数据库:
spring:
jpa:
database: H2
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create
properties:
hibernate.cache.use_second_level_cache: false
hibernate.cache.use_query_cache: false
generate-ddl: true
datasource:
url: jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false
username: sa
password: sa
driver-class-name: org.h2.Driver
测试本身(使用database-rider):
@Test
@DataSet(value = INITIAL, transactional = true)
void delete() {
Optional<MyEntity> v = repository.findByMyId(SECOND.getAttributeId());
assertThat(v.isPresent()).isTrue();
repository.delete(v.get());
v = repository.findByMyId(SECOND.getAttributeId());
}
测试的最后一行抛出以下异常:
Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:67)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:54)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:46)
at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3480)
at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3737)
at org.hibernate.action.internal.EntityDeleteAction.execute(EntityDeleteAction.java:99)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:478)
所有其他用于保存和查找的测试均按预期运行,仅使用删除 造成了这个。
我从其他帖子中尝试了几种建议的解决方案(this是类似的帖子,但是它不能解决我的问题)
答案 0 :(得分:1)
您是否尝试过使用@ExpectedDataSet?通过这种方式,您可以让dbrider在测试执行后断言数据库的状态:
@Test
@DataSet(value = INITIAL, transactional = true)
@ExpectedDataSet("expected.yml")
void delete() {
Optional<MyEntity> v = repository.findByMyId(SECOND.getAttributeId());
assertThat(v.isPresent()).isTrue();
repository.delete(v.get());
//v = repository.findByMyId(SECOND.getAttributeId()); let dbrider assert that for you
}
答案 1 :(得分:0)
您正在执行尚未提交的删除操作,然后尝试访问v = repository.findByMyId(SECOND.getAttributeId());
。