3

I have a project with Spring Boot + Gradle.

Let me paste some codes:

public class SolrData{
    private int sex;
    @JsonSerialize(using = CustomSexSerializer.class)
    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }
}

the code of CustomSexSerializer:

@Component
public class CustomSexSerializer extends JsonSerializer<Integer> {
    @Resource
    private MessageSource messageSource;

    @Override
    public void serialize(Integer value, JsonGenerator gen, SerializerProvider serializers)
            throws IOException, JsonProcessingException {
        Locale locale = LocaleContextHolder.getLocale();
        if(value == 0){
            gen.writeString(messageSource.getMessage("female", null, locale));
        }else if(value == 1){
            gen.writeString(messageSource.getMessage("male", null, locale));
        }else{
            gen.writeString(messageSource.getMessage("unknown", null, locale));
        }
    }
}

my properties is appplication.yml and the code of i18n:

spring.messages.basename: i18n/messages
spring.messages.encoding: UTF-8

the internationalization file is located in src/main/resource/i18n , there are three file: messages.properties /messages_en_US.properties /messages_zh_CN.properties. and it's defined 'male' filed. enter image description here

My testing code:

@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomSexSerializerTest {
    SolrData solrData;

    @Test
    public void testSerializeIntegerJsonGeneratorSerializerProvider() throws JsonProcessingException {
        solrData = new SolrData();
        solrData.setSex(1);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(solrData));
        Assert.assertEquals("男", solrData.getSex());
    }

}

When I ran the test case, I got some error. I debug the code, messageSource is null in CustomSexSerializer class.

Anyone has ideas about this testing?

Please give me a hint.

Thanks!

Pari
  • 91
  • 5
  • This is due to the serializer not being a Spring managed bean. To fix that, you'll have to use some kind of helper (eg. `SpringBeanAutowiringSupport`). This is explained in the duplicate question. You also have to use the Spring managed `ObjectMapper`, so rather than creating your own instance in your test, use `@Autowired` in your test to get an `ObjectMapper`. – g00glen00b Sep 27 '17 at 09:26

0 Answers0