Skip to content

Mocked MessageSource executes real method #46003

@andreasarf

Description

@andreasarf

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:

  1. Have a service class that include MessageSource as a bean.
  2. Create a test class for that service class.
    • Use SpringExtension
    • Mock all dependencies using MockBean
    • Mock the behavior of the method getMessage using Mockito.when
  3. 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

Activity

wilkinsona

wilkinsona commented on Jun 18, 2025

@wilkinsona
Member

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 match org.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:

@MockBean(name = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME)
added
status: invalidAn issue that we don't feel is valid
for: stackoverflowA question that's better suited to stackoverflow.com
and removed on Jun 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    for: stackoverflowA question that's better suited to stackoverflow.comstatus: invalidAn issue that we don't feel is valid

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @wilkinsona@spring-projects-issues@andreasarf

        Issue actions

          Mocked MessageSource executes real method · Issue #46003 · spring-projects/spring-boot