Android Studio中的java JUnit未正确使用货币格式
注意:我正在使用安装程序Google nowrecommends在Android Studio中进行JUnit测试
我试图对一段代码进行单元测试,该代码将货币值存储为double,并以该货币的格式输出字符串。我用java.text.NumberFormat
来做这件事:
public NumberFormat viewFormat;
public NumberFormat editFormat;
public CurrencyField(String languageCode, String countryCode) {
viewFormat = NumberFormat.getCurrencyInstance(new Locale(languageCode, countryCode));
viewFormat.setRoundingMode(RoundingMode.FLOOR);
下面是我想要格式化以显示的值:
public String getDisplayValue()
{
double numberValue = (double) mValue.getValue();
return mField.viewFormat.format(numberValue);
}
当我将代码作为Android应用程序的一部分运行时,数字的格式是正确的。例如,如果我使用以色列谢克尔作为我的货币,我会打电话给
Field currencyField = new CurrencyField("he", "ISR");
其中"he"
和"ISR"
分别是希伯来语和以色列语的代码。如果数字在内部存储为双精度45.12
,则输出为字符串"45.12 ₪"
,这是正确的。然而,当我尝试使用JUnit运行相同的代码时,测试结果如下:
org.junit.ComparisonFailure:
Expected :45.12 ₪
Actual :¤ 45.12
在我看来,JUnit或Android Studio在测试期间不知何故丢失了一些Java库。我甚至无法通过编程获得预期值的谢克尔符号。我试着用java.util.Currency
,但没用,然后我试了
expectedDisplayValue += ((CurrencyField) field).viewFormat.getCurrency().getSymbol(new Locale("he", "ISR"));
这也没用。我必须明确定义
private String expectedDisplayValue = "45.12 ₪";
为什么格式化在运行时有效,但在测试中无效
# 1 楼答案
结果证明我使用了错误的ISO 3166-1国家代码。我使用的是alpha 3代码(“ISR”)而不是alpha 2代码(“IL”),后者在应用程序中有效,但在测试中无效。当我使用希伯来语时,测试仍然会给我错误的符号和格式,但我会问另外一个问题。同时,我将使用其他外币进行测试