LocaleBasedFloatConverter implements Converter<Float> { public Float convert(String value, Class<? extends Float> type, ResourceBundle bundle) { if (isNullOrEmpty(value)) { return null; } try { final Locale locale = localization.getLocale(); DecimalFormat fmt = (DecimalFormat) DecimalFormat.getInstance(locale); return fmt.parse(value).floatValue(); } catch (ParseException e) { throw new ConversionError(MessageFormat.format(bundle.getString("is_not_a_valid_number"), value)); } } LocaleBasedFloatConverter(Localization localization); Float convert(String value, Class<? extends Float> type, ResourceBundle bundle);  }
@Test public void shouldBeAbleToConvertWithPTBR() { when(request.getAttribute("javax.servlet.jsp.jstl.fmt.locale.request")).thenReturn("pt_BR"); assertThat(converter.convert("10,00", Float.class, bundle), is(equalTo(new Float("10.00")))); assertThat(converter.convert("10,01", Float.class, bundle), is(equalTo(new Float("10.01")))); }
@Test public void shouldBeAbleToConvertWithENUS() { when(request.getAttribute("javax.servlet.jsp.jstl.fmt.locale.request")).thenReturn("en_US"); assertThat(converter.convert("10.00", Float.class, bundle), is(equalTo(new Float("10.00")))); assertThat(converter.convert("10.01", Float.class, bundle), is(equalTo(new Float("10.01")))); }
@Test public void shouldUseTheDefaultLocale() throws ParseException { when(request.getSession()).thenReturn(session); when(request.getAttribute("javax.servlet.jsp.jstl.fmt.locale.request")).thenReturn(null); when(session.getAttribute("javax.servlet.jsp.jstl.fmt.locale.session")). thenReturn(null); when(context.getAttribute("javax.servlet.jsp.jstl.fmt.locale.application")). thenReturn(null); when(context.getInitParameter("javax.servlet.jsp.jstl.fmt.locale")). thenReturn(null); when(request.getLocale()).thenReturn(Locale.getDefault()); DecimalFormat fmt = new DecimalFormat("##0,00"); fmt.setMinimumFractionDigits(2); Float theValue = new Float("10.00"); String formattedValue = fmt.format(theValue); assertThat(converter.convert(formattedValue, Float.class, bundle), is(equalTo(theValue))); }
@Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", Float.class, bundle), is(nullValue())); }
@Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, Float.class, bundle), is(nullValue())); }
@Test public void shouldThrowExceptionWhenUnableToParse() { when(request.getAttribute("javax.servlet.jsp.jstl.fmt.locale.request")).thenReturn("pt_br"); try { converter.convert("vr3.9", Float.class, bundle); fail("Should throw exception"); } catch (ConversionError e) { assertThat(e.getMessage(), is(equalTo("vr3.9 is not a valid number."))); } }