1
我有一個使用對象的活動。爲了測試,我想模擬這個對象,但我找不到如何讓一個Activity在onCreate()函數中使用模擬對象。如何獲得一個模擬對象到Activity的onCreate()?
我正在使用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);
}
}