我想测试整个Spring Batch,但是有问题。我有一项删除数据库和LDAP中的行的服务。 对于BD,我已经实现了H2内存数据库,所以没有问题。 对于LDAP,拥有内存中的LDAP更加困难,因此我想伪造DAO LDapRepository调用方法“删除”(LDapRepository是接口,而LDapRepositoryImpl由@Repository注释实现)
因此,我尝试在配置中注入一个模拟,但是它不起作用。 当我尝试进行假调用ldapRepository.removePerson时,测试失败并出现空指针异常(因此未正确注入ldapRepository)。
如何在我的配置中替换bean LDapRepository?
这是测试代码:
@ContextConfiguration(locations = {"classpath:purge/job-test.xml"})
public class PurgeJobTest {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@InjectMocks
@Qualifier(value = "ldapRepositoryImpl")
private LdapRepository ldapRepository;
@Test
public void testExampleJob() throws Exception {
Mockito.doNothing().when(ldapRepository.removePerson(any(String.class)));
JobParameters jobParameters = new JobParametersBuilder()
.addString("fichierJob", "/purge/job-test.xml")
.addString("nomJob", "purgeJob").toJobParameters();
JobExecution exec =jobLauncherTestUtils.launchJob(jobParameters);
assertEquals(BatchStatus.COMPLETED, exec.getStatus());
}
}
答案 0 :(得分:0)
好的,所以我承认我的问题有些棘手,但我想与其他面临类似问题的人分享答案。
空指针异常是很合理的。实际上,在上下文中未识别到该Bean,因为没有正确地将其注入其中。
这是本文Injecting Mockito Mock objects using Spring JavaConfig and @Autowired中与示例相关的常见陷阱。
或其他帖子:Injecting Mockito mocks into a Spring bean
因此,在我的job-test.xml中,我评论了组件扫描,在该组件扫描中声明了“真实的” LdapRepository”和LdapRepositoryImpl并将其替换为:
<bean id="ldapRepository" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="purge.batch.repository.LdapRepository" />
</bean>
<bean id="ldapRepositoryImpl" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="purge.batch.repository.LdapRepositoryImpl" />
</bean>
(我可以将这些bean声明放在组件扫描之前,以使其具有优先级)
那就像一个魅力!