0

I want to test a whole Spring Batch but Ihave a problem. I have a service to delete rows in a DB and in a LDAP. For the BD I have implemented a H2 in-memory database so no problems. For the LDAP it's more difficult to have a in-memory LDAP so I want to fake the DAO LDapRepository calling method "delete" (LDapRepository is the interface and LDapRepositoryImpl annotated by @Repository the implementation)

So I tried to inject a mock in my configuration but it doesn't work. The test fails with a null pointer exception when I try to make the fake call ldapRepository.removePerson (so ldapRepository is not correctly injected).

How is it possible to substitute the bean LDapRepository in my configuration ?

Here's the test code :

@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());

    }

} 
JavaLiker
  • 27
  • 6

1 Answers1

0

OK so I admit my question was a little tricky but I want to share the answer to other people who faced a similar problem.

The null pointer exception was quite logic. Indeed the bean was not recognized in the context because nowhere it was correctly injected in it.

It's a common pitfall related by example in this post Injecting Mockito Mock objects using Spring JavaConfig and @Autowired.

or this other post : Injecting Mockito mocks into a Spring bean

So in my job-test.xml I commented the component-scan in which my "real" LdapRepository" and LdapRepositoryImpl were declared and replace them with :

    <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>

(I could have place these bean declaration before the component-scan to give it priority)

And that works like a charm !

JavaLiker
  • 27
  • 6