001/*
002 * Copyright 2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *       https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.springframework.batch.test.context;
017
018import org.springframework.batch.test.JobLauncherTestUtils;
019import org.springframework.batch.test.JobRepositoryTestUtils;
020import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
021import org.springframework.beans.factory.support.BeanDefinitionRegistry;
022import org.springframework.beans.factory.support.RootBeanDefinition;
023import org.springframework.context.ConfigurableApplicationContext;
024import org.springframework.test.context.ContextCustomizer;
025import org.springframework.test.context.MergedContextConfiguration;
026import org.springframework.util.Assert;
027
028/**
029 * {@link ContextCustomizer} implementation that adds batch test utility classes
030 * ({@link JobLauncherTestUtils} and {@link JobRepositoryTestUtils}) as beans in
031 * the test context.
032 *
033 * @author Mahmoud Ben Hassine
034 * @since 4.1
035 */
036public class BatchTestContextCustomizer implements ContextCustomizer {
037
038        private static final String JOB_LAUNCHER_TEST_UTILS_BEAN_NAME = "jobLauncherTestUtils";
039        private static final String JOB_REPOSITORY_TEST_UTILS_BEAN_NAME = "jobRepositoryTestUtils";
040
041        @Override
042        public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
043                ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
044                Assert.isInstanceOf(BeanDefinitionRegistry.class, beanFactory,
045                                "The bean factory must be an instance of BeanDefinitionRegistry");
046                BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
047
048                registry.registerBeanDefinition(JOB_LAUNCHER_TEST_UTILS_BEAN_NAME,
049                                new RootBeanDefinition(JobLauncherTestUtils.class));
050                registry.registerBeanDefinition(JOB_REPOSITORY_TEST_UTILS_BEAN_NAME,
051                                new RootBeanDefinition(JobRepositoryTestUtils.class));
052        }
053
054}