gpt4 book ai didi

java - 使用 Robolectric 测试 Android DecimalFormat

转载 作者:行者123 更新时间:2023-12-05 07:53:16 26 4
gpt4 key购买 nike

Android 库修改了 DecimalFormat class加上一些不错的补充。当然,我需要添加其中一项(有效数字表示法:@)。

当我使用 Robolectric 进行测试时,似乎标准 Java DecimalFormat使用了类,这使我的测试失败。

有没有办法告诉 Robolectric 使用 Android 版本?或者我应该在我的项目中包含 DecimalFormat(从 AOSP 复制/粘贴类?)?

这是一个精简的例子:

如果我在具有以下设备的设备上运行该应用程序:

import java.text.DecimalFormat;
import java.util.Locale;

public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
DecimalFormat decimalFormat = (DecimalFormat)java.text.NumberFormat.getInstance(Locale.US);
decimalFormat.applyPattern("@@@");
Log.d('SO', decimalFormat.format(0.0567467));
}
}

它显示:

W/App: 0.0567

在单元测试中:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import java.text.DecimalFormat;
import java.util.Locale;

import static junit.framework.TestCase.assertEquals;


@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class NumberFormatTest {
@Test
public void testSignificantDigit() {
DecimalFormat decimalFormat = (DecimalFormat)java.text.NumberFormat.getInstance(Locale.US);
decimalFormat.applyPattern("@@@");
assertEquals("0.0567", decimalFormat.format(0.0567467));
}
}

运行测试将输出:

junit.framework.ComparisonFailure:

Expected :0.0567

Actual :@@@0

最佳答案

作为official android documentation指出,在 Android 运行时 (ART) 中运行 Java 代码时提供的实现不同于常规 JVM 中的实现。

RoboElectric 不在普通 Android 手机或模拟器上运行测试,而是在 JVM 上运行。在您的主机系统上运行的这个 JVM 没有 DecimalFormat 的这个修改后的运行时实现版本。因此,据我所知,在 JVM 中运行测试代码时,Android 提供的功能不可用。为了能够使用它,请在 Android 手机上运行测试,但是无论如何您都可以摆脱 RoboElectric 进行该测试,但使用 offered testing tools .

另一个逻辑问题:为什么要测试Android类?我猜谷歌已经为那里的变化编写了测试并跟踪它,所以you should no test functionality offered to you by the system you're using .

关于java - 使用 Robolectric 测试 Android DecimalFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32864889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com