How to simulate a user, click on a list item in unit testing?

I am trying to write a junit test case to select a list item and intent for the next action, but I don't know how to simulate this user action using junit coding. Can anyone help?

Also I want to ask if there is any material teaching a function or syntax for simlate various user actions in junit?

Below is an example from my curriculum tutorials, and I want to do something like this, but in a listview element.

public void testKilosToPounds() { 

 /* INTERACTIONS */ 
 TouchUtils.tapView(this, textKilos); // tap the EditText textKilos 
 sendKeys("1"); // sent the number 1 
 TouchUtils.clickView(this, buttonPounds); // click the button buttonPounds 

 /*CHECK THE RESULT*/ 
 double pounds; 
 try { 
 pounds = Double.parseDouble(textPounds.getText().toString()); 
 } catch (NumberFormatException e) { 
 pounds = -1; 
 } 

 //JUnit Assert equals 

 // message expected actual delta for comparing doubles 
 assertEquals("1 kilo is 2.20462262 pounds", 2.20462262, pounds, DELTA); 
 }
+4
source share
2 answers

ListView, , , TouchUtils.clickView.

ListView view ActivityInstrumentationTestCase2 this, p :

TouchUtils.clickView(this, view.getChildAt(p));

, , .

+1

JUnit , Android. , - . , click (InfoActivity) , . InfoActivity - , ListActivity.

public class ListActivityTest extends ActivityInstrumentationTestCase2<ListActivity> {

private Activity activity;
private ListView lv;
private InfoActivity contextInfoActivity;
private TextView tvInfo;

public  ListActivityTest(){
    super(ListActivity.class);
}



@Override
protected void setUp() throws Exception {
    super.setUp();
    activity = (ListActivity)getActivity();
    lv = (ListView)activity.findViewById(R.id.lv);

}

public void testCase1(){
    assertNotNull(activity);
    assertNotNull(lv);
}

public void testCase2(){

    Instrumentation instrumentation = getInstrumentation();
    Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(InfoActivity.class.getName(), null, false);

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {

            lv.performItemClick(lv,4,0);
            //lv is listview,4 is item position,0 is default id
        }
    });

    Activity currentActivity = getInstrumentation().waitForMonitor(monitor);
    contextInfoActivity = (InfoActivity) currentActivity;

    assertNotNull(contextInfoActivity);
    tvInfo = (TextView)contextInfoActivity.findViewById(R.id.tvInfo);

    assertNotNull(tvInfo);
    assertEquals("Karan",tvInfo.getText().toString());
    //karan is name at position 4 in listview and i am checking it with name set in textview of next activity i.e infoActivity.

}


@Override
protected void tearDown() throws Exception {
    super.tearDown();

    activity = null;
    lv = null;
    tvInfo = null;
    contextInfoActivity = null;

}

, . , - .

+1

Source: https://habr.com/ru/post/1539157/


All Articles