Skip to content

Instantly share code, notes, and snippets.

@tamboer
Last active December 18, 2017 13:55
Show Gist options
  • Select an option

  • Save tamboer/1d1b01525b454f7c4d67d4df4b0307be to your computer and use it in GitHub Desktop.

Select an option

Save tamboer/1d1b01525b454f7c4d67d4df4b0307be to your computer and use it in GitHub Desktop.
LOcale language converter null
/**
Use this in persistent model
@Column
@NotNull
@Convert(converter = LocaleConverter.class)
private Locale language;
*/
import javax.persistence.AttributeConverter;
import java.util.Locale;
public class LocaleConverter implements AttributeConverter<Locale, String> {
@Override
public String convertToDatabaseColumn(Locale language) {
return language == null ? null : language.toLanguageTag();
}
@Override
public Locale convertToEntityAttribute(String language) {
return language == null ? null : new Locale(language);
}
}
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(MockitoJUnitRunner.class)
public class LocaleConverterTest {
private final static Locale LOCALE = new Locale("nl");
private final static String VALUE = "nl";
private LocaleConverter localeConverter;
@Before
public void setup() {
localeConverter = new LocaleConverter();
}
@Test
public void convertToDatabaseColumnConvertsCorrectly() {
String result = localeConverter.convertToDatabaseColumn(LOCALE);
assertThat(result).isEqualTo(VALUE);
}
@Test
public void convertToDatabaseColumnConvertsNullToNull() {
String result = localeConverter.convertToDatabaseColumn(null);
assertThat(result).isNull();
}
@Test
public void convertToEntityAttributeConvertsCorrectly() {
Locale result = localeConverter.convertToEntityAttribute(VALUE);
assertThat(result).isEqualTo(LOCALE);
}
@Test
public void convertToEntityAttributeConvertsNullToNull() {
Locale result = localeConverter.convertToEntityAttribute(null);
assertThat(result).isNull();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment