vendredi 1 mai 2015

Mockito rule not being applied

I was writing a testcase using Mockito and it seems to me one Mockito rules does not get defined. Below is my scenario.

public class DummyTest {
   private final String[] alphabet= {"a", "b", "c", "d", "e" };
   private final String[] numeric= {"1", "2", "3", "4", "5" };
   AtomicInteger idx;
   String currentAlphabet;
   String currentNumeric;
   int currentIndex;
   Dummy dummyObj;

   private ruleSetUp() {

       dummyObj = Mockito.spy(new Dummy());
        // Rule for rs.next()
         Mockito.doAnswer(new Answer<Boolean>() {

        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            currentIndex = idx.getAndIncrement();
            if (alphabet.length > currentIndex) {
                currentAlphabet= alphabet[currentIndex];
                currentNumeric= numeric[currentIndex];
                return true;
            } else
                return false;
        };
    }).when(rs).next();

   // Rule for rs.getInt()
   Mockito.doAnswer(new Answer<Integer>() {

        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            return idx.get() - 1;
        };
    }).when(rs).getInt(2);

    // Rule for rs.getByte()
    Mockito.doAnswer(new Answer<byte[]>() {

        @Override
        public byte[] answer(InvocationOnMock invocation) throws Throwable {
            return currentNumeric.getBytes(StandardCharsets.UTF_8);
        };
    }).when(rs).getBytes(1);

       Mockito.doReturn(currentAplhabet).when(dummyObj).innerMethod(Mockito.anyInt(), Mockito.anyInt());
  }

  @Test
  public void methodTest(){


       ruleSetUp();

  }
}

The MEthod that I am testing is below:

class Dummy {

       public void method(int param1) {

          /*   some code  */
          param2 = xyz() ;  // Some mathematical calculation
          while(rs.next()) {

              byte[] strByte = rs.getBytes(1); 
              int number = rs.getInt(2);

              String str= new String(strByte, StandardCharset.UTF-8);
              // TEst Case rule causes below value to be always null
              String alphabet = innerMethod(param1, param2);               
          }

       }
}

On executing this test method, the value of alphabet in the method being tested is always found to be null. The value of 'str' is populated correctly depending upon correct value of currentNumeric. The loop also runs the correct number of times.

I am confused why the rule of innerMethd() is not being applied. I am not getting any error, just value being populated is always null irrespective of which iteration the loop is going through.

Can you guys please point out where I am going wrong and a way to get around it?

Thanks

Aucun commentaire:

Enregistrer un commentaire