我有一个使用对象的Activity。为了测试我想模拟这个对象,但是我找不到如何让一个Activity在onCreate()函数中使用mock对象。
我正在使用AndroidMock在测试中创建模拟对象和Robotium。例如:
应用程序(标准Android项目):
class MainActivity extends ... {
MyObject obj;
MainActivity() {
obj = new MyObject();
}
void onCreate(Bundle b) {
obj.doSomething();
...
}
}
测试(标准Android测试项目):
class MainActivityTest extends ... {
@UsesMocks(MyObject.class)
public void testMyObject() {
// create the mock object
MyObject o = AndroidMock.createMock(MyObject.class);
AndroidMock.expect(o.doSomething()).andReturn(false);
AndroidMock.replay(o);
// Here some code which makes the activity use the mock object
// and calls the onCreate() function on the activity.
// Do some tests on the activity.
Solo solo = new Solo(getInstrumentation(), getActivity());
Assert.assertTrue(solo.searchText("It works!"));
AndroidMock.verify(o);
}
}
答案 0 :(得分:2)
我知道两种方式。
使用DI容器。 Robojuice
@inject
MyObject obj;
继承要测试的类
活性
class DummyMainActivity extends MainActivity {
Bundle b;
@Override
void onCreate(Bundle b) {
this.b = b;
}
void onCreateSuper() {
super(b);
}
}
测试
class MainActivityTest extends ActivityUnitTestCase<DummyMainActivity> {
@UsesMocks(MyObject.class)
public void testMyObject() {
// create the mock object
MyObject o = AndroidMock.createMock(MyObject.class);
DummyMainActivity activity = startActivity(new Intent(), null, null);
activity.obj = o;
activity.onCreateSuper();
AndroidMock.verify(o);
}
}