我第一次在安卓应用中使用ui自动化测试是在几年前使用robotium(译者注:robotium是android中的一个自动化测试框架)。我认为测试环境越逼真越好。在最终测试中应当表现得如同超人一般能够迅速的点击任意一个位置而且并不会报错,对吧?我认为mocking测试很糟糕。为什么我们需要在测试的时候改变应用的行为[Java] 查看源文件 复制代码
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写在一起,便于直观理解)
[Java] 查看源文件 复制代码
@module
public class applicationmodule {
@provides
@singleton
public datamanager providedatamanager() {
return mdatamanager;
}
}
@singleton
@component(modules = applicationmodule.class)
public interface applicationcomponent {
datamanager datamanager();
}
应用的applicationcomponent 在application类中初始化:
[Java] 查看源文件 复制代码
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
[Java] 查看源文件 复制代码
@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
[Java] 查看源文件 复制代码
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将会是下面这个样子:
[Java] 查看源文件 复制代码
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 请求失败,那么界面会显示“加载用户名失败”
下面依次展示三个测试:
[Java] 查看源文件 复制代码
@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层的单元测试。