mercredi 2 mars 2016

Mockito mock setter() and override getter()

I am not doing a unitTesting on Android Application.

TextChoiceAdapter.java:

public class TextChoiceAdapter extends ArrayAdapter<String> {
    public Context context;
    public int selectedPosition = -1;   //Otherwise Android set zero then choice A will be selected automatically
    public void choiceSelection(View rowView, int position){
        if (selectedPosition == position)
            rowView.setBackgroundColor(0xA0FF8000); // orange
        else
            rowView.setBackgroundColor(Color.TRANSPARENT);
    }
    public TextChoiceAdapter(Context context,int resources, List<String> textChoiceList) {
        super(context, resources, textChoiceList);
        this.context = context;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
      ...
    }
}

TextChoiceAdapterTest.java:

public class TextChoiceAdapterTest{
    private TextChoiceAdapter textChoiceAdapter;
    private ArrayList<String> textChoiceList;
    @Before
    public void setUp(){
        textChoiceList = new ArrayList<>();
        textChoiceList.add("North");
        textChoiceList.add("East");
        textChoiceList.add("West");
        textChoiceList.add("South");
        Context context = mock(Context.class);
        textChoiceAdapter = new TextChoiceAdapter(context, 1, textChoiceList);
    }
    @Test
        public void testChoiceSelection(){
    //http://ift.tt/1TmWxcO

    textChoiceAdapter.selectedPosition = 1;
    Context context = mock(Context.class);

    //Try my own object class.
    class mockRowView extends View{
        int backgroundColor;
        public mockRowView(Context context){
            super(context);
        }
        public void setBAckgroundColor(int a){
            this.backgroundColor = a;
        }
        public int getBackgroundColor(){
            return this.backgroundColor;
        }
    }
    View rowView = mock(mockRowView.class);
    textChoiceAdapter.choiceSelection(rowView, 1);
    assertEquals(rowView.getBackgroundColor(), 0xA0FF8000);
}
}

Error:
java.lang.AssertionError: Expected :null Actual :-1593868288

My question:
How to mock my rowView with setter() and getter() properly?
I want different answer from different input.

I am imitating Mockito: how to stub getter setter

Aucun commentaire:

Enregistrer un commentaire