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 examples.springbatch.mapper.PersonMapper;
22 import org.apache.ibatis.session.SqlSession;
23 import org.apache.ibatis.session.SqlSessionFactory;
24 import org.junit.jupiter.api.Test;
25 import org.mybatis.dynamic.sql.render.RenderingStrategies;
26 import org.mybatis.dynamic.sql.select.CountDSL;
27 import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
28 import org.springframework.batch.core.ExitStatus;
29 import org.springframework.batch.core.job.JobExecution;
30 import org.springframework.batch.core.step.StepExecution;
31 import org.springframework.batch.infrastructure.item.ExecutionContext;
32 import org.springframework.batch.test.JobOperatorTestUtils;
33 import org.springframework.batch.test.context.SpringBatchTest;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
36
37 @SpringBatchTest
38 @SpringJUnitConfig(classes = BulkInsertConfiguration.class)
39 class SpringBatchBulkInsertTest {
40
41 @Autowired
42 private JobOperatorTestUtils jobOperatorTestUtils;
43
44 @Autowired
45 private SqlSessionFactory sqlSessionFactory;
46
47 @Test
48 void testThatRowsAreInserted() throws Exception {
49
50 assertThat(rowCount()).isZero();
51
52 JobExecution execution = jobOperatorTestUtils.startJob();
53 assertThat(execution.getExitStatus()).isEqualTo(ExitStatus.COMPLETED);
54 assertThat(numberOfRowsProcessed(execution)).isEqualTo(TestRecordGenerator.recordCount());
55
56
57 assertThat(rowCount()).isEqualTo(TestRecordGenerator.recordCount());
58 }
59
60 private int numberOfRowsProcessed(JobExecution jobExecution) {
61 return jobExecution.getStepExecutions().stream()
62 .map(StepExecution::getExecutionContext)
63 .mapToInt(this::getRowCount)
64 .sum();
65 }
66
67 private int getRowCount(ExecutionContext executionContext) {
68 return executionContext.getInt("row_count", 0);
69 }
70
71 private long rowCount() {
72 try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
73 PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
74
75 SelectStatementProvider selectStatement = CountDSL.countFrom(person)
76 .build()
77 .render(RenderingStrategies.MYBATIS3);
78
79 return personMapper.count(selectStatement);
80 }
81 }
82 }