Android单元测试 - 代码引用android类时的最佳实践

Edu*_*ysh 9 junit android unit-testing android-testing

我有一个常规的JUnit测试用例来测试非android方法逻辑.该方法将TextUtils用于TextUtils.isEmpty()之类的东西.

我只是为了引入TextUtils类而使它成为AndroidTestCase是没有意义的.有没有更好的方法来测试这个单元测试?喜欢将android.jar添加到测试项目或其他什么?

与我想要模拟Context对象的另一个测试类似的情况.如果不扩展AndroidTestCase,我无法嘲笑它.在这些情况下,我只是尝试测试非Android逻辑并且不希望它在模拟器上运行,但它触及一些Android类的最佳实践是什么?

谢谢

小智 5

您有两种方法可以为Android代码运行测试.首先是仪表化测试选项,您可以通过将adb连接到系统来测试代码.

第二个也是更实用的方法是JUnit Testing,只测试你的Java类,并且模拟所有其他Android相关的东西.

使用PowerMockito

在类名上面添加它,并包含任何其他CUT类名(测试中的类)

@RunWith(PowerMockRunner.class)
@PrepareForTest({TextUtils.class})
public class ContactUtilsTest
{
Run Code Online (Sandbox Code Playgroud)

将此添加到您的@Before

@Before
public void setup(){
PowerMockito.mockStatic(TextUtils.class);
mMyFragmentPresenter=new MyFragmentPresenterImpl();
}
Run Code Online (Sandbox Code Playgroud)

这将使PowerMockito返回TextUtils中方法的默认值

例如,假设您的实现是在@Test中检查字符串是否为空

when(TextUtils.isEmpty(any(CharSequence.class))).thenReturn(true);
//Here i call the method which uses TextUtils and check if it is returning true
assertTrue(MyFragmentPresenterImpl.checkUsingTextUtils("Fragment");
Run Code Online (Sandbox Code Playgroud)

您还必须添加相关的gradle依赖项

testCompile "org.powermock:powermock-module-junit4:1.6.2"
testCompile "org.powermock:powermock-module-junit4-rule:1.6.2"
testCompile "org.powermock:powermock-api-mockito:1.6.2"
testCompile "org.powermock:powermock-classloading-xstream:1.6.2"
Run Code Online (Sandbox Code Playgroud)


pjc*_*jco 3

也许看看http://robolectric.org/

它模拟了大部分 Android SDK,因此测试可以在纯 Java 中运行。这意味着它们可以在常规桌面虚拟机中运行得更快。

有了这样的速度,测试驱动开发就成为可能。