模拟一种在Android中获取代码覆盖率的方法

时间:2014-02-22 01:20:29

标签: java android unit-testing mocking opengl-es-2.0

我正在以测试驱动的方式编写Android OpenGL ES 2.0应用程序。这是我的代码。

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         boolean checkCompatability = checkForDeviceCompatablity();


         if(checkCompatability)
         {
                Toast.makeText(this, "Your device is opengl compatible", Toast.LENGTH_LONG).show();

         }
         else
         {
            Toast.makeText(this, "Your device does not support OpenGL", Toast.LENGTH_LONG).show();
         }
    }

    public boolean checkForDeviceCompatablity() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

        ConfigurationInfo info = manager.getDeviceConfigurationInfo();
        boolean result = info.reqGlEsVersion >= 0x20000
            || (Build.VERSION.SDK_INT
                    >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1);

        return result;
    }

}

这是我的考试

public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {

    private MainActivity mActivity;

    public MainActivityTest(Class<MainActivity> activityClass) {
        super(activityClass);
    }

    public MainActivityTest(){
        super(MainActivity.class);
    }

    //The below method would always return me a true as I test it in a real device.
    public void testIntegrationCheckForConfiguration() {
        mActivity = getActivity();
        mActivity.startActivity(mActivity.getIntent());
        boolean resultConfiguration = mActivity.checkForDeviceCompatablity();
        assertNotNull(resultConfiguration);
    }

    //I need to mock the above method into something like the below method so that I can get coverage for the else block.
    public void testCheckForConfigurationWhenDeviceIsOfInCorrectConfiguration(){
        mActivity = new MainActivity(){
            @Override
            public boolean checkForDeviceCompatablity() {
                return false;
            }
        };
        mActivity.startActivity(mActivity.getIntent());
        boolean compatability = mActivity.checkForDeviceCompatablity();
        assertTrue(compatability);
    }
}

我知道我做错了。但我需要一种方法来模拟checkForDeviceCompatability以使其返回false。当我运行测试时,我在startActivity调用时得到NullPointerException。如何模拟函数checkForDeviceCompatability并获取代码覆盖MainActivity类中的else部分?

对于任何类型的模拟框架,这也是可能的吗?

1 个答案:

答案 0 :(得分:0)

并非我对这类事情有太多经验,但您可以尝试Mockito

在将Dagger依赖注入集成到我的应用程序时,在示例中注意到它。