Spring Batchユニットテストの例
このチュートリアルでは、jUnitおよびTestNGフレームワークを使用してSpringバッチジョブを単体テストする方法を示します。 バッチジョブを単体テストするには、spring-batch-test.jar、@autowired、JobLauncherTestUtilsを宣言し、ジョブまたはステップを起動して、実行ステータスをアサートします。
1. 単体テストの依存関係
Springバッチを単体テストするには、次の依存関係を宣言します。
pom.xml
org.springframework.batch
spring-batch-core
2.2.0.RELEASE
org.springframework.batch
spring-batch-infrastructure
2.2.0.RELEASE
org.springframework.batch
spring-batch-test
2.2.0.RELEASE
junit
junit
4.11
test
org.testng
testng
6.8.5
test
2. 春のバッチジョブ
単純なジョブで、後で実行ステータスを単体テストします。
spring-batch-job.xml
3. jUnitの例
ジョブを起動し、実行ステータスをアサートします。
AppTest.java
package com.example;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:spring/batch/jobs/spring-batch-job.xml",
"classpath:spring/batch/config/context.xml",
"classpath:spring/batch/config/test-context.xml"})
public class AppTest {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Test
public void launchJob() throws Exception {
//testing a job
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
//Testing a individual step
//JobExecution jobExecution = jobLauncherTestUtils.launchStep("step1");
assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
}
}
P.S Assume context.xml is declared all the require Spring batch core components, like jobRepository and etc.
このJobLauncherTestUtilsは手動で宣言する必要があります。
test-context.xml
4. TestNGの例
TestNGフレームワークの同等の例。
AppTest2.java
package com.example;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;
@ContextConfiguration(locations = {
"classpath:spring/batch/jobs/spring-batch-job.xml",
"classpath:spring/batch/config/context.xml",
"classpath:spring/batch/config/test-context.xml"})
public class AppTest2 extends AbstractTestNGSpringContextTests {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Test
public void launchJob() throws Exception {
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
Assert.assertEquals(jobExecution.getStatus(), BatchStatus.COMPLETED);
}
}
完了しました。
ソースコードをダウンロード
ダウンロード–SpringBatch-UnitTest-Example.zip(83 KB)