通过JMockit调用私有方法来测试结果

Rob*_*ram 14 java junit jmockit private-methods

我使用JMockit 1.1,我想做的就是调用私有方法并测试返回值.但是,我无法从JMockit De-Encapsulation示例中了解如何执行此操作.

我试图测试的方法是这个类中的私有方法:

public class StringToTransaction {
   private List<String> parseTransactionString(final String input) {
      // .. processing
      return resultList;
   }
}
Run Code Online (Sandbox Code Playgroud)

我的测试代码如下.

@Test
public void testParsingForCommas() {
   final StringToTransaction tested = new StringToTransaction();
   final List<String> expected = new ArrayList<String>();
   // Add expected strings list here..
   new Expectations() {
      {
         invoke(tested, "parseTransactionString", "blah blah");
         returns(expected);
      }
   };
}
Run Code Online (Sandbox Code Playgroud)

而我得到的错误是:

java.lang.IllegalStateException:此时缺少对mocked类型的调用; 请确保仅在声明合适的模拟字段或参数后才会出现此类调用

也许我在这里误解了整个API,因为我认为我不想模拟这个类..只是测试调用私有方法的结果.

Jef*_*son 34

我认为你这太复杂了.您根本不应该使用Expectations块.你需要做的就是这样:

@Test
public void testParsingForCommas() {
   StringToTransaction tested = new StringToTransaction();
   List<String> expected = new ArrayList<String>();
   // Add expected strings list here..

   List<String> actual = Deencapsulation.invoke(tested, "parseTransactionString", "blah blah");
   assertEquals(expected, actual);
}
Run Code Online (Sandbox Code Playgroud)

基本上,通过Deencapsulation调用一个私有方法并测试实际值是否等于预期值.就像你公开的方法一样.没有嘲笑,所以不需要Expectations阻止.