MockBean annotation in Spring Boot test causes NoUniqueBeanDefinitionException

I had the same "issue" in spring-boot 2.3.9 but it's not a bug, it's problem with the configuration of beans.

At least, There are two ways to solve it:

Set name parameter in @MockBean annotation:

In the test, add a name to MockBean:

@MockBean(name="myRepository")
private MyRepository diffrentName;

and in the production codebase use myRepository as filed name :

@Autowired
private MyRepository myRepository;

The name of @MockBean must be the same as the name of the field.

Name a MockBean filed the same as a dependency in code.

In the test, use the correct name of MockBean filed:

@MockBean
private MyRepository customRepository;

and in the production codebase use customRepository as filed name :

@Autowired
private MyRepository customRepository;

in that way, You indicate which bean You want to use.

I hope this will be helpful for someone.


It's a bug: https://github.com/spring-projects/spring-boot/issues/6541

The fix is in spring-data 1.0.2-SNAPSHOT and 2.0.3-SNAPSHOT : https://github.com/arangodb/spring-data/issues/14#issuecomment-374141173

If you aren't using these version, you can work around it by declaring the mock with its name:

@MockBean(name="myMongoRepository")
private MyMongoRepository repository;

In response to your comment

From Spring's doc:

For convenience, tests that need to make REST calls to the started server can additionally @Autowire a TestRestTemplate which will resolve relative links to the running server.

Reading this, I think you need to declare @SpringBootTest with a web environment:

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

If your spring boot doesn't start the web environment, then what is the need for TestRestTemplate. Thus, I guess spring does not even make it available.