TextWatcher方法&运行robolectric测试时不会调用overrideTerite.onTextChanged()

时间:2013-01-15 17:18:52

标签: android unit-testing robolectric

我做了一个非常简单的Android活动:

public class SimpleActivity extends Activity {

private EditText editText1;
private EditText editText2;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout verticalLayout = new LinearLayout(this);
    verticalLayout.setOrientation(LinearLayout.VERTICAL);
    editText1 = new EditText(this) {
        @Override
        protected void onTextChanged(CharSequence text, int start,
                int lengthBefore, int lengthAfter) {
            // TODO Auto-generated method stub
            super.onTextChanged(text, start, lengthBefore, lengthAfter);
        }
    };
    editText1.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            System.out.println(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
    editText1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
    verticalLayout.addView(editText1);
    editText2 = new EditText(this);
    editText2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
    verticalLayout.addView(editText2);
    setContentView(verticalLayout);
}

public EditText getEditText1() {
    return editText1;
}

public EditText getEditText2() {
    return editText2;
}

}

当我在Android设备上运行此代码时,都覆盖了EditText.onTextChanged()方法&在引入组件时调用TextWatcher.onTextChanged()方法。当我调用方法editText1.setText(“text”)

时,它们也被正确调用

当我在Roboelectric测试跑步者中创建SimpleActivity时,它已经创建了& editText1 / editText2不为null,但EditText.onTextChanged()&组件init&组件时不调用TextWatcher.onTextChanged();在调用EditText.setText()时 如何使TextWatcher工作?它是我应用程序中的重要组成部分。如果不处理文本更改事件,则无法进行测试。

请帮忙。

1 个答案:

答案 0 :(得分:0)

使用Robolectric 1.1,我测试了这段代码:

@RunWith(RobolectricTestRunner.class)
public class TestSimpleActivity {

    @Test
    public void testMethod() {
        SimpleActivity activity = new SimpleActivity();
        activity.onCreate(null);
        activity.getEditText1().setText("hello world");
    }

}

我能够看到TextWatcher.onTextChanged()触发,但不能看到EditText.onTextChanged()。如果两人都解雇了,那将是理想的,但请看https://github.com/pivotal/robolectric/blob/robolectric-1.1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextView.java#L63。看起来TextWatcher会触发,但onTextChange()似乎没有为子类实现。

如果您需要该功能,则必须在Robolectric中实施。不幸的是,Robolectric在实施方面存在差距。