ActivityUnitTestCase与PreferenceScreen

时间:2013-10-07 18:58:17

标签: android tdd sharedpreferences

我有一个新创建的android-18应用程序,其中PreferenceScreen非常明显&很容易列出。

我还有一个自动化测试[已修复将问题转换为答案]。

public class MyPreferenceTest extends ActivityUnitTestCase<MyPreference> {  
    Intent intent;
    MyPreference activity;

    public MyPreferenceTest() {
        super(MyPreference.class);
    }

    @Override
    protected void setUp() throws Exception {
        Context targetContext = getInstrumentation().getTargetContext();
        intent = new Intent(targetContext, MyPreference.class);
        super.setUp();
    }

    private void assembleActivity() {
        startActivity(intent, null, null);
        activity = getActivity();
    }

    private void assemblePreferences(String device, String userName, String password) {
        Context targetContext = getInstrumentation().getTargetContext();        
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(targetContext);
        SharedPreferences.Editor editor = sharedPref.edit();

        editor.putString("smart_phin_bluetooth_devices", device);
        editor.putString("username", userName);  
        editor.putString("password", password);  
        editor.commit();
    }

    public void test_empty_userNames_dont_reflect_into_the_summary() {
        assemblePreferences("", "", ""); 
        assembleActivity();
        activity.onResume();
        EditTextPreference userName = (EditTextPreference) activity.findPreference("username");  // FIXME  userName
        assertEquals("", userName.getEditText().getText().toString());
        assertEquals("", userName.getText());
        assertEquals("Enter your user name", userName.getSummary().toString());
    }

    public void test_full_userNames_reflect_into_the_summary() {
        assemblePreferences("", "BookerT", "");
        assembleActivity();

        activity.onResume();  //  We must call this bc Android does but the test rig does not...
        EditTextPreference userName = (EditTextPreference) activity.findPreference("username");
        assertEquals("username", userName.getKey());

        assertEquals("BookerT", String.valueOf(userName.getText().toString());
//        assertEquals("BookerT", userName.getEditText().getText().toString());
        assertEquals("BookerT", userName.getSummary().toString());
    }

}  // end of class MyPreferenceTest

注释掉的断言会失败,因为还没有调用EditText视图。

现在,测试检查onResume()中的新代码是否从通用词汇中更新摘要以反映首选项的当前值。

1 个答案:

答案 0 :(得分:1)

您的测试中存在错误。

private void assemblePreferences(String device, String userName, String password)

请注意,此处的值顺序为deviceuserNamepassword

assemblePreferences("BookerT", "", "");

因此deviceBookerT,而不是userName