java - 如何在 Spring Batch Junit 测试中模拟 writer?
问题描述
我正在使用 Junit 测试 Spring Batch 应用程序:
这是我的工作 xml 配置:
<!-- parse queue -->
<batch:step id="parseQueue">
<batch:tasklet>
<batch:chunk
reader="readQueue"
processor="processQueue"
writer="customItemWriter"
commit-interval="100">
</batch:chunk>
</batch:tasklet>
</batch:step>
我正在测试“parseQueue”步骤。
我正在使用 JobLauncherTestUtils 来测试如下步骤:
jobLauncherTestUtils.launchStep("parseQueue");
问题是它运行整个步骤代码。我的意思是阅读器、处理器和编写器。我想跳过 Writer 的执行。
有没有办法做到这一点?
关于在 Spring Batch 中模拟“Writer”有什么建议吗?
我试图嘲笑作家。它不模拟,真正的 Writer 实现被调用。通常,它会起作用,但它似乎不适用于 Spring Batch。
提前致谢。
下面是我的测试类的代码:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:/job/qhandler-job.xml",
"classpath:/spring/qhandler-applicationContext.xml" })
public class TestReader {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Mock
CustomItemWriter writer;
@InjectMocks
private ReadQueueMsgFromWs reader;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testReader() throws UnexpectedInputException, ParseException, NonTransientResourceException, Exception
{
jobLauncherTestUtils.launchStep("parseQueue");
}
}
解决方案
在 IT 场景中,您使用@MockBean
stub 容器管理的 bean。
尝试这个:
@MockBean
CustomItemWriter writer;
@Autowired
private ReadQueueMsgFromWs reader;
你也不需要在@InjectMocks
这里使用。