lundi 5 septembre 2016

How can I mock and test this class?

The follows was the code which I want to test.

public class Demo {

   private static final List<Pair<String, String>> mList;

   static {
     mList = new ArrayList<>();
     mList.add(new Pair<>("F0", "T1"));
     mList.add(new Pair<>("F1", "T2"));
     mList.add(new Pair<>("F2", "T3"));
   }

   public String getStr(int pos) {
     return mList.get(pos).first;
   }
}

I was an android developer. I have get some trouble in test and mock the code.I have use mockito. I have try some code to test it,but the result was not my expect.

1.First try

@Test
public void test(){
    Demo demo=new Demo();
    assertEquals(demo.getStr(0),"F0");
    /**
    *  java.lang.AssertionError: 
    *  Expected :null 
    *  Actual   :F0
    */
}

2.Second try

@Test
public void test() {
    Demo demo = mock(Demo.class);

    doCallRealMethod().when(demo).getStr(0);
    assertEquals(demo.getStr(0), "F0");
    /**
     *  java.lang.AssertionError: 
     *  Expected :null
     *  Actual   :F0
     */
}

Anyone tell me how can I resolve this problem to make demo.getStr(0) == "F0" by call the real method? Thanks!

Aucun commentaire:

Enregistrer un commentaire