1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package examples.springbatch.bulkinsert;
17
18 import static examples.springbatch.mapper.PersonDynamicSqlSupport.*;
19 import static org.assertj.core.api.Assertions.assertThat;
20
21 import org.apache.ibatis.session.SqlSession;
22 import org.apache.ibatis.session.SqlSessionFactory;
23 import org.junit.jupiter.api.Test;
24 import org.mybatis.dynamic.sql.render.RenderingStrategies;
25 import org.mybatis.dynamic.sql.select.CountDSL;
26 import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
27 import org.springframework.batch.core.ExitStatus;
28 import org.springframework.batch.core.JobExecution;
29 import org.springframework.batch.core.StepExecution;
30 import org.springframework.batch.item.ExecutionContext;
31 import org.springframework.batch.test.JobLauncherTestUtils;
32 import org.springframework.batch.test.context.SpringBatchTest;
33 import org.springframework.beans.factory.annotation.Autowired;
34 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
35
36 import examples.springbatch.mapper.PersonMapper;
37
38 @SpringBatchTest
39 @SpringJUnitConfig(classes = BulkInsertConfiguration.class)
40 class SpringBatchBulkInsertTest {
41
42 @Autowired
43 private JobLauncherTestUtils jobLauncherTestUtils;
44
45 @Autowired
46 private SqlSessionFactory sqlSessionFactory;
47
48 @Test
49 void testThatRowsAreInserted() throws Exception {
50
51 assertThat(rowCount()).isZero();
52
53 JobExecution execution = jobLauncherTestUtils.launchJob();
54 assertThat(execution.getExitStatus()).isEqualTo(ExitStatus.COMPLETED);
55 assertThat(numberOfRowsProcessed(execution)).isEqualTo(TestRecordGenerator.recordCount());
56
57
58 assertThat(rowCount()).isEqualTo(TestRecordGenerator.recordCount());
59 }
60
61 private int numberOfRowsProcessed(JobExecution jobExecution) {
62 return jobExecution.getStepExecutions().stream()
63 .map(StepExecution::getExecutionContext)
64 .mapToInt(this::getRowCount)
65 .sum();
66 }
67
68 private int getRowCount(ExecutionContext executionContext) {
69 return executionContext.getInt("row_count", 0);
70 }
71
72 private long rowCount() {
73 try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
74 PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
75
76 SelectStatementProvider selectStatement = CountDSL.countFrom(person)
77 .build()
78 .render(RenderingStrategies.MYBATIS3);
79
80 return personMapper.count(selectStatement);
81 }
82 }
83 }