-
Notifications
You must be signed in to change notification settings - Fork 41.3k
Not planned
Labels
for: stackoverflowA question that's better suited to stackoverflow.comA question that's better suited to stackoverflow.comstatus: invalidAn issue that we don't feel is validAn issue that we don't feel is valid
Description
Problems:
When mocking org.springframework.context.MessageSource
, it will execute real method instead of mocked behavior.
org.springframework.context.NoSuchMessageException: No message found under code 'billing.cycle.created' for locale 'en_ID'.
at org.springframework.context.support.DelegatingMessageSource.getMessage(DelegatingMessageSource.java:76)
Steps to reproduce:
- Have a service class that include
MessageSource
as a bean. - Create a test class for that service class.
- Use
SpringExtension
- Mock all dependencies using
MockBean
- Mock the behavior of the method
getMessage
usingMockito.when
- Use
- Run the test.
Actual: throw exception and it seems to call real method.
Expected: no exception and returns the output specified via Mockito
Can use this code as a reference: https://github.com/andreasarf/simple-billing-engine/pull/1/files
NOTE: I have tried using the latest version of Spring Boot which uses MockitoBean
and the faulty behavior is still there.
Details:
- Spring Boot 3.3.4
- Java 21
Metadata
Metadata
Assignees
Labels
for: stackoverflowA question that's better suited to stackoverflow.comA question that's better suited to stackoverflow.comstatus: invalidAn issue that we don't feel is validAn issue that we don't feel is valid
Type
Projects
Milestone
Relationships
Development
Select code repository
Activity
wilkinsona commentedon Jun 18, 2025
This behavior is to be expected given your test's configuration.
There's no existing
MessageSource
bean in the context so, as described in its javadoc,@MockBean
generates a name. This generated name does not matchorg.springframework.context.support.AbstractApplicationContext#MESSAGE_SOURCE_BEAN_NAME
so the context does not use the mocked message source.To fix the problem, you should specify the name when mocking the bean: