javajunit5

jUnit Spring Batch 5


I have this class:

    package com.example.demo;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
public class JobConfiguration {

    @Bean
    public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
        return new JobBuilder("job", jobRepository)
                .start(new StepBuilder("step", jobRepository)
                        .tasklet((contribution, chunkContext) -> {
                            System.out.println("hello world");
                            return RepeatStatus.FINISHED;
                        }, transactionManager)
                        .build())
                .build();
    }
}

I would like to create class JobConfigurationTest to test with jUnit. can you help me please (how to mock 'PlatformTransactionManager ')


Solution

  • firstly, you should follow program to interface rule which's mean you should change method signature job(JobRepository jobRepository, TransactionManager transactionManager) so it'll be easy to test like following

    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.extension.ExtendWith;
    import org.mockito.InjectMocks;
    import org.mockito.Mock;
    import org.mockito.junit.jupiter.MockitoExtension;
    import org.springframework.batch.core.Job;
    import org.springframework.batch.core.repository.JobRepository;
    import org.springframework.transaction.TransactionManager;
    
    import static org.junit.jupiter.api.Assertions.assertNotNull;
    
    @ExtendWith(MockitoExtension.class)
    public class JobConfigurationTest {
    
        @Mock
        private JobRepository jobRepository;
    
        @Mock
        private TransactionManager transactionManager;
    
        @InjectMocks
        private JobConfiguration jobConfiguration;
    
        @Test
        public void testJobConfiguration() {
            Job job = jobConfiguration.job(jobRepository, transactionManager);
            assertNotNull(job, "Job should not be null");
        }
    }