0
我正在以測試驅動的方式編寫Android OpenGL ES 2.0應用程序。這裏是我的代碼。模擬在Android中獲取代碼覆蓋率的方法
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部分?
這是可能的任何類型的嘲諷框架?
是的,我認爲這也是一種選擇,但是我會通過創建對象並啓動startActivity來做同樣的事情,這會再次導致我出現NullPointerException異常。 – Wizard