当前位置: 移动技术网 > 移动技术>移动开发>Android > Android 中构建快速可靠的 UI 测试

Android 中构建快速可靠的 UI 测试

2019年07月24日  | 移动技术网移动技术  | 我要评论

前言

让我一起来看看 iván carballo和他的团队是如何使用espresso, mockito 和dagger 2 编写250个ui测试,并且只花了三分钟就运行成功的。

在这篇文章中,我们会探索如何使用mockito(译者注:mockito是java编写的一个单元测试框架),dagger 2 去创建快速可靠的android ui测试。如果你正在开始编写android中的ui 测试或者希望改善已有测试性能的开发者,那么这篇文章值得一读。

我第一次在安卓应用中使用ui自动化测试是在几年前使用robotium(译者注:robotium是android中的一个自动化测试框架)。我认为测试环境越逼真越好。在最终测试中应当表现得如同超人一般能够迅速的点击任意一个位置而且并不会报错,对吧?我认为mocking测试很糟糕。为什么我们需要在测试的时候改变应用的行为?那不是欺骗吗?几个月后我们有了大概100个测试用例要花费40分钟去运行起来。它们是如此的不稳定,即使应用的功能上并没有任何错误,通常有一大半的几率会运行失败。我们花了大量的时间去编写它们,但是这些测试用例却没有帮我们找到任何问题。

但正如john dewey所说,失败是具有启发意义的。
失败是有启发意义的。智者总能从失败和成功中学到同样多的东西。

我们确实学到。我们认识到在测试中依赖于真实的api 接口是一个糟糕的做法。因为你失去了对返回的数据结果的控制,你也就不能对你的测试做预先处理。也就是说网络错误和外部api接口错误都会导致你的测试出错。如果你的wifi出错了,你肯定不希望你的测试也会跟着出错。你当然希望这时ui测试能够成功运行。如果你还依赖外部的api接口那么你完全是在做集成测试(integration tests),也就得不到我们期望的结果。

mock测试正式解决之道

(mocking is the solution)

mock 测试也就是通过一个模拟(mock)的对象去替换一个真实的对象以便于测试。它主要应用于编写单元测试,但在ui测试中也会非常有用。你可以参照不同的方法去模拟java对象但使用mockito 确实是一个简单有效的解决方案。在下面的例子中你可以看到一个模拟的userapi 类并且stub(译者注:stub,也即“桩”,主要出现在集成测试的过程中,从上往下的集成时,作为下方程序的替代。可以理解为对方法进行预先的处理,达到修改的效果。下文中不做翻译)了其中的一个方法,因此它总会返回一个用户名username的静态数组。

class usersapi {
string[] getusernames() { }
}
// create the mock version of a usersapi class

usersapi mockapi = mockito.mock(usersapi.class);

// stub the getusernames() method 

when(mockapi.getusernames())

.thenreturn(new string[]{"user1", "user2", "user3"});

// the call below will always return an array containing the

// three users named above

mockapi.getusernames();

一旦你创建了一个mock对象你需要确保应用测试的时候使用的是这个模拟的对象,并且在运行的时候使用的是真实对象。这也是一个难点所在,如果你的代码构建得并不是易于测试(test-friendly)的,替换真实对象的过程会变得异常艰难甚至是说不可能完成。还要注意的是,你想要模拟的代码必须独立到一个单独的类里面。比如说,如果你直接从你的activity中使用httpurlconnection调用rest api 进行数据访问(我希望你不要这么做), 这个操作过程模拟起来也就会非常困难。

在测试之前考虑一下系统架构,糟糕的系统架构往往会导致测试用例和mock测试难于编写,mock测试也会变得不稳定。

一个易于测试的架构

a test friendly architecture

构建一个易于测试的架构有许多种方式。在这里我将使用 ribot 中使用的架构 (译者注:也就是在开篇提到的android应用架构)作为范例,你也可以应用这样的架构方式到任何架构中。我们的架构是基于mvp模式,我们决定在ui测试中去模拟(mock)整个model层,因此我们可以对数据由更多的操作性,也就能够写出更有价值和可靠的测试。

mvp架构

datamanager是model层中唯一暴露给presenter层的数据的类,因此为了测试model层我们只需要替换为一个模拟
的datamanger即可。

使用dagger注入模拟的datamanager

using dagger to inject a mock datamanager

一旦我们明确了需要模拟什么对象,那么接下来就该考虑在测试中如何替换真实的对象。我们通过dagger2 解决这个问题(一个android中的依赖注入框架),如果你还没有接触过dagger ,在继续阅读下去之前我建议你阅读使用dagger2 进行依赖注入【英】 。我们的应用至少包含一个dagger 的module和component。通常被叫做applicationcomponent 和applicationmodule。你可以在下面看到一个简化版的只提供了datamanger实例的类。当然你也可以采用第二种方法,在datamanager的构造函数上使用@inject注解。这里我直接提供一个方法便于理解。(译者注:这里将两个类applicationcomponent 和applicationmodule写在一起,便于直观理解)

@module

public class applicationmodule {

@provides

@singleton

public datamanager providedatamanager() {

return mdatamanager;

}

}

@singleton

@component(modules = applicationmodule.class)

public interface applicationcomponent {

datamanager datamanager();

}

应用的applicationcomponent 在application类中初始化:

public class myapplication extends application {

applicationcomponent mapplicationcomponent;

public applicationcomponent getcomponent() {

if (mapplicationcomponent == null) {

mapplicationcomponent = daggerapplicationcomponent.builder()

.applicationmodule(new applicationmodule(this))

.build();

}

return mapplicationcomponent;

}

// needed to replace the component with a test specific one

public void setcomponent(applicationcomponent applicationcomponent) {

mapplicationcomponent = applicationcomponent;

}

}

如果你使用过dagger2,你可能有同样的配置步骤,现在的做法是创建一个test的时候需要用到的module和component

@module

public class testapplicationmodule {

// we provide a mock version of the datamanager using mockito

@provides

@singleton

public datamanager providedatamanager() {

return mockito.mock(datamanager.class);

}

}

@singleton

@component(modules = testapplicationmodule.class)

public interface testcomponent extends applicationcomponent {

// empty because extends applicationcomponent

}

上面的testapplicationmodule使用mockito提供了模拟的datamanger对象,testcomponent是applicationcomponent的继承类,使用了testapplicationmodule作为module,而不是applicationmodule。这也就意味着如果我们在我们的application类中初始化testcomponent会使用模拟的datamanager对象。

创建junit,并且设定testcomponent

creating a junit rule that sets the testcomponent

为了确保在每次测试前testcomponent被设置到application类中,我们可以创建junit 4 的 testrule

public class testcomponentrule implements testrule {

private final testcomponent mtestcomponent;

private final context mcontext;

public testcomponentrule(context context) {

mcontext = context;

myapplication application = (myapplication) context.getapplicationcontext();

mtestcomponent = daggertestcomponent.builder()

.applicationtestmodule(new applicationtestmodule(application))

.build();

}

public datamanager getmockdatamanager() {

return mtestcomponent.datamanager();

}

@override

public statement apply(final statement base, description description) {

return new statement() {

@override

public void evaluate() throws throwable {

myapplication application = (myapplication) context.getapplicationcontext();

// set the testcomponent before the test runs

application.setcomponent(mtestcomponent);

base.evaluate();

// clears the component once the tets finishes so it would use the default one. 

application.setcomponent(null);

}

};

}

}

testcomponentrule将会创建testcomponent的实例对象,这也就会覆写apply方法并返回一个新的 statement,新的statement会:

1 设定testcomponent给application类的component对象。

2调用基类的statement 的evaluate()方法(这是在test的时候执行)

3 设置application的component字段为空,也就让其恢复到初始状态。我们能够通过这种方式预防测试用例之间的相互影响
通过上面的代码我们可以通过getmockdatamanager()方法获取模拟的datamanager对象。这也就允许我们能够给得到datamanager对象并且stub它的方法。需要注意的是,这只有testapplicationcomponent的providedatamanger方法使用@singleton注解的时候有效。如果它没有被指定为单例的,那么我们通过getmockdatamanager方法得到的实例对象将会不同于应用使用的实例对象。因此,我们也不可能stub它。

编写测试用例

writing the tests

现在我们有dagger正确的配置,并且testcomponentrule也可以使用了,我们还有一件事要做,那就是编写测试用例。我们使用 espresso编写ui测试。它并不是完美的但是它是一个快速可靠的android测试框架。在编写测试用例之前我们需要一个app去测试。假如我们有一个非常简单的app,从rest api 中加载用户名,并且展示到recyclerview上面。那么datamanger将会是下面这个样子:

public datamanager {

// loads usernames from a rest api using a retrofit

public single<list<string>> loadusernames() {

return musersservice.getusernames();

}

}

loadusername()方法使用retrofit和rxjava 去加载rest api 的数据。它返回的是single 对象,并且发送一串字符串。 我们也需要一个activity展示用户名usernames到recyclerview上面,我们假设这个activity叫做usernamesactivity。如果你遵循mvp模式你也会有相应的presenter但为了直观理解,这里不做presenter操作。

现在我们想要测试这个简单的 activity有至少三个情况需要测试:

1如果api返回一个有效的用户名列表数据,那么它们会被展示到列表上面。
2 如果api返回空的数据,那么界面会显示“空的列表”
3 如果api 请求失败,那么界面会显示“加载用户名失败”

下面依次展示三个测试:

@test

public void usernamesdisplay() {

// stub the datamanager with a list of three usernames

list<string> expectedusernames = arrays.aslist("joe", "jemma", "matt");

when(component.getmockdatamanager().loadusernames())

.thenreturn(single.just(expectedusernames));

// start the activity

main.launchactivity(null);

// check that the three usernames are displayed

for (sting username:expectedusernames) {

onview(withtext(username))

.check(matches(isdisplayed()));

}

}

@test

public void emptymessagedisplays() {

// stub an empty list

when(component.getmockdatamanager().loadusernames())

.thenreturn(single.just(collections.emptylist()));

// start the activity

main.launchactivity(null);

// check the empty list message displays

onview(withtext("empty list"))

.check(matches(isdisplayed()));

}

@test

public void errormessagedisplays() {

// stub with a single that emits and error

when(component.getmockdatamanager().loadusernames())

.thenreturn(single.error(new runtimeexception()));

// start the activity

main.launchactivity(null);

// check the error message displays

onview(withtext("error loading usernames"))

.check(matches(isdisplayed()));

}

}

通过上面的代码,我们使用testcomponentrule 和android 官方测试框架提供的activitytestrule。activitytestrule会让我们从测试中启动usernamesactivity 。注意我们使用 rulechain 来确保 testcomponentrule总是在activitytestrule前运行。这也是确保testcomponent在任何activity运行之前在application类中设定好。

你可能注意到了三个测试用例遵循同样的构建方式:

1 通过when (xxx).thenreturn(yyy)设置前置条件。这是通过stub loadusernames()方法实现的。例如,第一个测试的前置条件是有一个有效的用户名列表。
2 通过main.launchactivity(null)运行activity。
3 通过check(matches(isdisplayed()));检查视图的展示,并且展示相应前置条件期望的值。

这是一个非常有效的解决方案,它允许你测试不同的场景,因为你对整个application的初始状态拥有绝对的控制权。如果你不使用mock来编写上面的三个用例,几乎不可能达到这样的效果因为真实的api接口总会返回同样的数据。

如果你想要查看使用这个测试方法的完整实例,你可以在github查看项目ribot android boilerplate 或者 ribot app.
当然这个解决方案也有一些瑕疵。首先在每个test之前都会stub显得非常繁琐。复杂的界面可能需要在每个测试之前有5-10个stub。将一些stub移到初始化setup()方法中是有用的但经常不同的测试需要不同的stub。第二个问题是ui测试和潜在的实现存在着耦合,也就意味着如果你重构datamanager,那么你也需要修改stub。

虽然这样,我们也在ribot 的几个应用中应用了这个ui测试方法,事实证明这中方法也是有好处的。例如,我们最近的一个android应用中有250个ui测试能够在三分钟之内运行成功。其中也有380个model层和presenter层的单元测试。

好了,我希望这篇文章让你对ui测试的认知以及编写更好的测试代码有一个很好的帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网