Skip to content

Instantly share code, notes, and snippets.

@hikoz
Created October 28, 2010 07:03
Show Gist options
  • Save hikoz/650808 to your computer and use it in GitHub Desktop.
Save hikoz/650808 to your computer and use it in GitHub Desktop.
targetsに作りたい型を放り込んでおけばMockitoがMockを作ってSpringに登録してくれる
import org.mockito.Mockito;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
public class MocksRegistry implements BeanFactoryPostProcessor {
private Class<?>[] targets;
public void setTargets(Class<?>[] targets) {
this.targets = targets;
}
@Override
public void postProcessBeanFactory(
final ConfigurableListableBeanFactory context)
throws BeansException {
BeanDefinitionRegistry registry = ((BeanDefinitionRegistry) context);
for (Class<?> clazz : targets) {
register(registry, clazz);
}
}
private void register(final BeanDefinitionRegistry registry,
final Class<?> type) {
RootBeanDefinition definition = new RootBeanDefinition(
MocksFactory.class);
MutablePropertyValues values = new MutablePropertyValues();
values.addPropertyValue(new PropertyValue("type", type));
definition.setPropertyValues(values);
registry.registerBeanDefinition("factoryOf" + type.getSimpleName(),
definition);
}
public static class MocksFactory<T> implements FactoryBean<T> {
private Class<T> type;
public void setType(final Class<T> type) {
this.type = type;
}
@Override
public T getObject() throws Exception {
return Mockito.mock(type);
}
@Override
public Class<T> getObjectType() {
return type;
}
@Override
public boolean isSingleton() {
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment