如何在@Transactional SpringBootTest 测试用例中测试 spring 批处理作业? [英] How to test spring batch job within @Transactional SpringBootTest test case?
问题描述
我今天好像赢不了...
I just can't seem to win today...
- 有没有办法从 Spock SpringBootTest 集成测试中的
OneToMany
关系中读取数据,而无需将测试注释为@Transactional
或添加不切实际的spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
? - 或者,有没有办法从
@Transactional
测试用例中启动 Spring-Batch 作业?
- Is there a way to read from a
OneToMany
relationship in a Spock SpringBootTest integration test, without annotating the test as@Transactional
or adding the unrealisticspring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
? - OR, is there a way to launch a Spring-Batch Job from within a
@Transactional
test case?
让我详细说明...
我正在尝试让一个简单的 Spring Boot 集成测试适用于我的 Spring Batch 报告流程,该流程从复杂的 DB2 表网络中读取数据,并为感兴趣的系统生成一系列更改消息.我正在使用 Groovy Spock 测试框架和一个 H2 内存数据库,其中填充了我的 DB2 表数据的代表性切片.
I'm trying to get a simple Spring Boot Integration test working for my Spring Batch reporting process, which reads from tangled web of DB2 tables and generates a series of change messages for interested systems. I'm using the Groovy Spock testing framework and an H2 in-memory database filled with a representative slice of my DB2 tables' data.
在测试开始时,我试图使用给定表中的每个实体来在驱动我的消息传递的更改跟踪表中生成条目.
At the beginning of the test, I'm attempting to use every entity from a given Table to generate entries in a change-tracking table that drives my messaging.
setup:
List allExistingTestPeople = peopleRepository.findAll()
Collections.shuffle(allExistingTestPeople)
allExistingTestPeople?.each { Person person ->
Nickname nicknames = person.nicknames
nicknames?.each { Nickname nickname ->
changeTrackingRepository.save(new Change(personId: person.id, nicknameId: nickname.id, status: NEW))
}
}
将这些作为我的 DB2 域类:
Given these as my DB2 domain classes:
@Entity
@Table(name = "T_PERSON")
public class Person {
@Id
@Column(name = "P_ID")
private Integer id;
@Column(name = "P_NME")
private String name;
@OneToMany(targetEntity = Nickname.class, mappedBy = "person")
private List<Nickname> nicknames;
}
@Entity
@Table(name = "T_NICKNAME")
public class Nickname{
@EmbeddedId
private PersonNicknamePK id;
@Column(name = "N_NME")
private String nickname;
@ManyToOne(optional = false, targetEntity = Person.class)
@JoinColumn(name = "P_ID", referencedColumnName="P_ID", insertable = false, updatable = false)
private Person person;
}
@Embeddable
public class PersonNicknamePK implements Serializable {
@Column(name="P_ID")
private int personId;
@Column(name="N_ID")
private short nicknameId;
}
但是我收到了这个 LazyInitializationException,即使我在测试用例的上下文中从 OneToMany
关系中读取...
But I'm getting this LazyInitializationException, even though I'm reading from that OneToMany
relationship within the context of a test case...
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.my.package.db2.model.Person.nicknames, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:602)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:217)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:161)
at org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:350)
我在网上看到了用 @Transactional
注释来注释我的测试用例的建议,这确实让我更进一步,让我可以从这个 OneToMany
关系中读取.但是,当我尝试启动 Spring Batch Job 时,我想从我的 when
子句中进行测试:
I came across the advice online to annotate my test case with the @Transactional
annotation, which definitely got me a little further, allowing me to read from this OneToMany
relationship. However, when I then attempt to launch the Spring Batch Job I'd like to test from my when
clause:
@Transactional
def "Happy path test to validate I can generate a report of changes"() {
setup:
//... See above
when:
service.launchBatchJob()
then:
//... Messages are generated
}
我收到一个异常,即无法从事务上下文启动 Spring Batch 作业!即使我通过 ResourcelessTransactionManager
和 MapJobRepositoryFactoryBean
使用内存中的作业管理器,因为这只是我正在编写的一个短暂的计划脚本......
I'm getting the exception that a Spring Batch Job can't be launched from the context of a transaction! Even though I'm using an in-memory Job manager via ResourcelessTransactionManager
and MapJobRepositoryFactoryBean
, since this is just a short lived scheduled script I'm writing...
java.lang.IllegalStateException: Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove @Transactional annotations from client).
at org.springframework.batch.core.repository.support.AbstractJobRepositoryFactoryBean$1.invoke(AbstractJobRepositoryFactoryBean.java:177)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy125.createJobExecution(Unknown Source)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:134)
at com.my.package.service.MyService.launchBatchJob(MyService.java:30)
到目前为止似乎唯一可行的是,如果我取消了 @Transactional
注释,而是将 spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
添加到我的application-test.properties
文件.但是,这似乎不是一个很好的主意,因为它不现实 - 如果我添加它,那么即使我的代码中由于延迟初始化异常而存在错误,我也永远不会在测试中看到它.
The only thing that seems to work so far is if I scrap the @Transactional
annotation and instead add spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
to my application-test.properties
file. BUT, this doesn't seem like a very good idea, because it's not realistic - if I add this, then even if there's a bug in my code due to a lazy-initialization-exception, I'd never see it in the tests.
对不起小说,希望有人能指出我正确的方向:(
Sorry for the novel, hoping someone can point me in the right direction :(
还有我的内存中 Spring-Batch 配置,我尝试关闭事务验证.不幸的是,虽然这让我更进一步,但 Spring Batch 分区器的自动装配 EntityManager 突然无法在 H2 数据库中运行查询.
Also here's my In-memory Spring-Batch configuration, in which I've tried turning off the transaction validation. Unfortunately, while this gets me a little further, the Spring Batch partioner's autowired EntityManager is suddenly failing to run queries in the H2 database.
@Configuration
@EnableBatchProcessing
public class InMemoryBatchManagementConfig {
@Bean
public ResourcelessTransactionManager resourceslessTransactionManager() {
ResourcelessTransactionManager resourcelessTransactionManager = new ResourcelessTransactionManager();
resourcelessTransactionManager.setNestedTransactionAllowed(true);
resourcelessTransactionManager.setValidateExistingTransaction(false);
return resourcelessTransactionManager;
}
@Bean
public MapJobRepositoryFactoryBean mapJobRepositoryFactory(ResourcelessTransactionManager txManager)
throws Exception {
MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean(txManager);
factory.setValidateTransactionState(false);
factory.afterPropertiesSet();
return factory;
}
@Bean
public JobRepository jobRepository(MapJobRepositoryFactoryBean factory) throws Exception {
return factory.getObject();
}
@Bean
public SimpleJobLauncher jobLauncher(JobRepository jobRepository) throws Exception {
SimpleJobLauncher launcher = new SimpleJobLauncher();
launcher.setJobRepository(jobRepository);
launcher.afterPropertiesSet();
return launcher;
}
@Bean
public JobExplorer jobExplorer(MapJobRepositoryFactoryBean factory) {
return new SimpleJobExplorer(factory.getJobInstanceDao(), factory.getJobExecutionDao(),
factory.getStepExecutionDao(), factory.getExecutionContextDao());
}
@Bean
public BatchConfigurer batchConfigurer(MapJobRepositoryFactoryBean mapJobRepositoryFactory,
ResourcelessTransactionManager resourceslessTransactionManager,
SimpleJobLauncher jobLauncher,
JobExplorer jobExplorer) {
return new BatchConfigurer() {
@Override
public JobRepository getJobRepository() throws Exception {
return mapJobRepositoryFactory.getObject();
}
@Override
public PlatformTransactionManager getTransactionManager() throws Exception {
return resourceslessTransactionManager;
}
@Override
public JobLauncher getJobLauncher() throws Exception {
return jobLauncher;
}
@Override
public JobExplorer getJobExplorer() throws Exception {
return jobExplorer;
}
};
}
}
推荐答案
您可以使用 TransactionTemplate
仅在事务中运行设置"(而不是在 @Transactional 中包含所有内容)
).不幸的是,交易将通过这种方式提交,您需要进行一些手动清理.
You can do transactions programmatically using TransactionTemplate
to run only the "setup" inside a transaction (instead of having everything in @Transactional
). Unfortunately this way the transaction will be committed and you will need to do some manual cleanup.
它可以像任何其他 bean 一样自动装配:
It can be autowired as any other bean:
@Autowired
private TransactionTemplate transactionTemplate;
...它是这样使用的:
...and it's used this way:
transactionTemplate.execute((transactionStatus) -> {
// ...setup...
return null; // alternatively you can return some data out of the callback
});
这篇关于如何在@Transactional SpringBootTest 测试用例中测试 spring 批处理作业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!