简体   繁体   中英

Is there any way to extend the @Configuration class to include the constructor parameter?

I am writing integration tests for a Spring Batch Project, which has the following configuration

@Configuration
@EnableScheduling
@PropertySource("application.properties")
public class BatchConfig(
     private JobBuilderFactory factory;
     public BatchConfig(JobBuilderFactory factory) {
           this.factory = factory;
     }
     
     @Bean
     public Step someStep {
       // step implementation
     }
}

I created the following base test class

@ContextConfiguration(classes=BatchConfig.class)
@SpringBootTest
public class BatchTestBase {
       @Autowired 
       Step someStep
}

When I extend this class and try running it, I get the following error

Parameter 0 of constructor in BatchConfig required a bean of type JobBuilderFactory that could not be found

Is there any way to extend BatchConfig to XML or add constructor parameters here to access the beans?

Create test context configuration and use together with a configuration witch need to test in @ContextConfiguration

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
        BatchTestBase.ContextConfiguration.class,
        BatchConfig.class
})
public class BatchTestBase {

    @Configuration
    static class ContextConfiguration {
        @Bean
        JobBuilderFactory factory() {
            //return fake, mock or stub
        }

    }

    @Autowired
    Step someStep;

    @Test
    public void shouldExecuteStep() {
       //some test
    }
}

Try to inject through set instead of constructor, as it follows :

 public setFactory(JobBuilderFactory factory) {
           this.factory = factory;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM