Hello team,

I am facing an issue and I couldn't find a way to solve this.

Before changing the spring boot version from 2.7.7 to 3.0.1 tests are passing

Mockito versions: core -> 4.8.1 (coming from spring-boot-starter-test:3.0.1) inline -> 4.11.0 (defined in pom.xml) junit-jupiter -> 4.8.1 (coming from spring-boot-starter-test:3.0.1)

<spring-boot.version>3.0.1</spring-boot.version>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>${spring-boot.version}</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <version>${spring-boot.version}</version>
    <scope>test</scope>
</dependency>

and @Spy annotated field is

@Spy
private DefaultListableBeanFactory defaultListableBeanFactory

Error Message:

org.mockito.exceptions.base.MockitoException: Unable to initialize @Spy annotated field 'defaultListableBeanFactory'.

Mockito cannot mock this class: class org.springframework.beans.factory.support.DefaultListableBeanFactory.

I just found that main cause is spring version change from 5.x to 6.x because when I changed the version of spring-beans to 5.3.24 tests are ok. but with version 6.x they are all failing. Mockito cannot mock DefaultListableBeanFactory class after spring version 6.x

Java : 17
JVM vendor name : Amazon.com Inc.
JVM vendor version : 17.0.5+8-LTS
JVM name : OpenJDK 64-Bit Server VM
JVM version : 17.0.5+8-LTS
JVM info : mixed mode, sharing
OS name : Mac OS X
OS version : 12.2.1

Can you help me to solve this problem?

If more details are needed I'm happy to provide. Thanks in advance.

Comment From: wilkinsona

The bean factory isn't a bean so you shouldn't be using @SpyBean to spy upon it. It may have worked previously, but that was by luck rather than design. You're also mixing artifacts from Mockito 4.8 and 4.11 which isn't supported.

Rather than trying to get this to work with Spring Framework 6.0.x, I would recommend taking a step back and reconsidering mocking or spying the bean factory at all. If you need some help with that, please follow up on Stack Overflow or Gitter as we prefer to only use the issue tracker for bugs and enhancements.