如何将一个模拟对象放入Activity的onCreate()中?

时间:2012-10-03 12:00:06

标签: android automated-tests

我有一个使用对象的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);
    }
}

1 个答案:

答案 0 :(得分:2)

我知道两种方式。

  1. 使用DI容器。 Robojuice

    @inject
    MyObject obj;
    
  2. 继承要测试的类

  3. 活性

        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);
            }
        }