【问题标题】:handle a function expecting different input and output which is mocked using EasyMock处理期望使用 EasyMock 模拟的不同输入和输出的函数
【发布时间】:2014-04-18 13:19:43
【问题描述】:

正在测试的函数通过不同的输入调用函数 findByNames 并期望不同的输出。我需要使用服务 uDao 来模拟它。那么我应该写两个不同的期望吗?但它不起作用......我应该如何处理这种情况?

  EasyMock.expect(uDao.findByNames(CollectionUtils.newArrayList(target1Username)))
                .andReturn(CollectionUtils.newArrayList(target1Group)).once();
 //code in between
 EasyMock.expect(uDao.findByNames(CollectionUtils.newArrayList(target1Username, ownerUsername)))
         .andReturn(CollectionUtils.newArrayList(target1Group, ownerGroup));

/*target1Username, ownerUsername are strings and target1Group,
   ownerGroup are of class    UserGroup
*/

【问题讨论】:

  • 也许我可以使用 EasyMock.expect(userGroupDao.findByNames(EasyMock.isA(List.class))).andReturn(CollectionUtils.newArrayList(target1Group, ownerGroup));但这显示错误,因为 findByNames 期待 Collection
  • “但它不起作用”是什么意思?您收到错误消息吗?
  • junit.framework.AssertionFailedError: java.lang.AssertionError: 意外的方法调用 findByNames([elementsuser1@elements.com, owner@ owner.com]): findByNames([elementsuser1@elements.com, owner@owner.com]): 预期:1,实际:0
  • 我不明白这个错误想说什么......
  • 在调试时我注意到 findByNames 的第一遍工作正常......但是对于 findByNames 的第二个期望,调试器抛出错误,甚至无法进入函数 findByNames

标签: unit-testing junit easymock


【解决方案1】:

您的失败信息:

<failure message="java.lang.AssertionError: Unexpected method call
     findByNames([elementsuser1@elements.com, owner@owner.com]): 
     findByNames([elementsuser1@elements.com, owner@owner.com]): expected: 1, actual: 0" 

暗示传入的集合不相等。

EasyMock 使用对象相等性来测试参数是否匹配。由于您说第一次调用findByNames 有效(使用Collection&lt;String&gt;)而第二次调用(使用Collection&lt;UserGroup&gt;)失败,我猜问题出在UserGroup 类。

传入的 Set 的 toString() 似乎具有与预期相同的 toString() 值,因此:

  1. UserGroup.equals() 方法检查未设置为相等值的附加字段或
  2. UserGroup 没有定义 equals 方法,所以使用默认的相等检查。默认的 equals 方法只说对象是相同的引用时它们是相等的。因此,具有相同值的两个不同实例将不相等。或
  3. (不太可能)CollectionUtils.newArrayList() 返回的 Collection 未正确实现 equals。我将假设此方法来自第 3 方库并正确实施。我只是把它放在这里,以防其他两种情况不能解决问题。

【讨论】:

  • 第二次调用也需要 Collection..输出是 Collection
  • 哦,那CollectionUtils.newArrayList() 的代码可能没有正确实现equals?
  • public static List newArrayList(final T... items) { List list = new ArrayList(); list.addAll(Arrays.asList(items));返回列表; }
  • CollectionUtils 中的函数 newArrayList() 如上所述
猜你喜欢
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
相关资源
最近更新 更多