通过JMockit调用私有方法以测试结果 [英] Invoking a private method via JMockit to test result

查看:614
本文介绍了通过JMockit调用私有方法以测试结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JMockit 1.1,我要做的就是调用一个私有方法并测试返回值.但是,我无法从 JMockit解封装中确切地了解如何执行此操作示例.

Am using JMockit 1.1 and all I want to do is invoke a private method and test the return value. However, I am having trouble understanding exactly how to do this from the JMockit De-Encapsulation example.

我要测试的方法是此类中的私有方法:

The method I am trying to test is the private method in this class:

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

下面是我的测试代码.

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

我得到的错误是:

java.lang.IllegalStateException:在以下位置缺少对模拟类型的调用 这点;请确保此类调用仅在 声明合适的模拟字段或参数

java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter

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

Perhaps I have misunderstood the whole API here, because I don't think I want to mock the class.. just test the result of calling the private method.

推荐答案

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

I think you are making this too complicated. You should not be using the Expectations block at all. All you need to do is something like this:

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

基本上,通过解封装调用私有方法,并测试实际值是否等于预期值.就像该方法是公共方法一样.无需进行任何模拟,因此不需要Expectations块.

Basically, call a private method via Deencapsulation and test that the actual is equal to the expected. Just like you would if the method were public. No mocking is being done, so no Expectations block is needed.

这篇关于通过JMockit调用私有方法以测试结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆