Mockito规则未被应用

时间:2015-05-01 20:24:07

标签: java unit-testing junit mocking mockito

我正在使用Mockito编写一个测试用例,在我看来,一个Mockito规则没有定义。以下是我的情景。

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();

  }
}

我正在测试的方法如下:

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);               
          }

       }
}

在执行此测试方法时,始终会发现正在测试的方法中的字母值为null。根据currentNumeric的正确值,正确填充'str'的值。循环也运行正确的次数。

我很困惑为什么没有应用innerMethd()的规则。我没有收到任何错误,只是填充的值总是为null,无论循环经历了哪个迭代。

你们可以指出我出错的地方以及解决问题的方法吗?

谢谢

0 个答案:

没有答案