MockitoPostProcessor.getExistingBeans checks the FactoryBean.OBJECT_TYPE_ATTRIBUTE on bean definitions but it only does a String match.

Framework expects a Class or ResolvableType

Comment From: bbulgarelli

Can I do this one?

Comment From: philwebb

You're welcome to take a look at this one @bbulgarelli. I'll assign it to you.

Comment From: wilkinsona

How's it going, @bbulgarelli?

Comment From: bbulgarelli

I'm having some trouble. I made the following change in MockitoPostProcessor.getExistingBeans:

private Set<String> getExistingBeans(ConfigurableListableBeanFactory beanFactory, ResolvableType type) {

        Set<String> beans = new LinkedHashSet<>(Arrays.asList(beanFactory.getBeanNamesForType(type, true, false)));
        String typeName = type.resolve(Object.class).getName();
        for (String beanName : beanFactory.getBeanNamesForType(FactoryBean.class, true, false)) {
            beanName = BeanFactoryUtils.transformedBeanName(beanName);
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
            Object attribute = beanDefinition.getAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE);
            if(attribute instanceof Class) {
                Class<?> attributeClass = (Class<?>) attribute;
                if (typeName.equals(attributeClass.getName())) {
                    beans.add(beanName);
                }
            } else if (attribute instanceof ResolvableType) {
                ResolvableType resolvableType = (ResolvableType) attribute;
                if (typeName.equals(resolvableType.resolve(Object.class).getName())) {
                    beans.add(beanName);
                }
            }
        }
        beans.removeIf(this::isScopedTarget);
        return beans;
    }

When I run the tests, one is always failing. I can't figure it out. I am also not sure if I should remove the string match or not.

Comment From: wilkinsona

Thanks for the progress update.

When I run the tests, one is always failing. I can't figure it out.

I guess it's canMockBeanProducedByFactoryBeanWithObjectTypeAttribute that's failing. It sets the attribute using a String but your changes mean that only a Class<?> or ResolvableType will be considered.

I am also not sure if I should remove the string match or not

Please keep the string match for now. There are some other projects that set the attribute with a String value and we should give them some time to adapt.

It would be good to update the tests so that in addition to the existing test for a String value, we also test the object type attribute with Class and ResolvableType values as well.

Comment From: wilkinsona

How's it going now, @bbulgarelli?

Comment From: bbulgarelli

How's it going now, @bbulgarelli?

Sorry for keeping you waiting. I have been very busy in the past few weeks. I have created a PR, and I believe it solves the issue.

Comment From: wilkinsona

Closing in favor of #36224. Thanks for the PR, @bbulgarelli.