message.properties key cannot be resolved from MessageSource.

I tried using "null" and "Locale.ENGLISH" for the locale, but both don't return a key. But when I run the same through the Validator interface, the error message is resolved correctly.

@SpringBootTest
public class PersonValidatorTest {
   //FAILURE
    @Test
    public void testMessageSource(@Autowired MessageSource messageSource) {
        assertEquals("Firstname missing", messageSource.getMessage("person.name", null, null));
        assertEquals("Firstname missing", messageSource.getMessage("person.firstname", null, Locale.ENGLISH));
    }

    //OK
    @Test
    public void testFieldValidation(@Autowired jakarta.validation.Validator validator) {
        PersonDto person = new PersonDto();
        Set<ConstraintViolation<PersonDto>> errors = validator.validate(person);
        errors.forEach(error -> assertEquals("Firstname missing", error.getMessage()));
    }

}

public class PersonDto {
    @jakarta.validation.constraints.NotBlank(message = "{person.firstname}")
    public String firstname;
}

/src/main/resources/messages.properties:
person.firstname=Firstname missing

Spring-boot-3.4.1

Result:

org.springframework.context.NoSuchMessageException: No message found under code 'person.name' for locale 'null'.

    at org.springframework.context.support.AbstractMessageSource.getMessage(AbstractMessageSource.java:162)
    at com.example.demo.PersonValidatorTest.testMessageSource(PersonValidatorTest.java:26)
    at java.base/java.lang.reflect.Method.invoke(Method.java:580)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)

Comment From: nosan

Your message.properties has the following:


person.firstname=Firstname missing

But you are trying to find a message using the key person.name.

Comment From: nosan

I've tried your example with a correct message key and all tests passed.

Comment From: membersound

Thanks, that was a typo. I will create the sample project again and report back.

Comment From: membersound

Sorry, reason was I pulled a commons library that itself brought a messages.properties with, and thus mine was overlayed.