0

How do I compare dynamic object types in Junit for example:-

while (objList.hasNext()) {
      Object<String> obj = objList.next();
      Assert.assertEquals("expected", obj); 
}

In this scenario if one occurrence is failed the whole test will fail. Is it a good approach if I use a condition before the assert test to pin point the expected String

like this:

while (objList.hasNext()) {
      Object<String> obj = objList.next();
      if (obj.equals("expected")) {
           Assert.assertEquals("expected", obj); 
      }
}

but in this case there's no point of having a Junit assert test. Because I'm already doing what Junit is intended to do Thanks.

4

4 回答 4

3

看看ErrorCollector Rule

它允许您“收集”错误并最终输出它们。如果您使用它,JUnit 不会在第一个错误时失败。

于 2012-09-14T09:33:13.897 回答
1

你在这里问什么并不完全清楚。如果我们知道你在迭代什么会更容易,但假设它是一个 Iterable,你最好看看hamcrest matchers

例如

asserThat(objList, Matchers.hasItem(expected);

如果期望等于您的可迭代元素中的元素,则将通过。查看与 junit 捆绑的匹配器,或将外部 hamcrest 库添加到您的测试项目中。

于 2012-09-14T13:55:24.677 回答
0

我为更大的数据结构做的是使用一个明智的 toString() 方法并比较它。

例如

assertEquals(""+expected, ""+obj);
assertEquals(expected, obj);

这样做的原因是通过 IDE(向您展示差异)或文本比较,您可以看到所有不同的值以及它们的不同之处。第二个检查是确认它们确实是相等的。

于 2012-09-14T09:32:36.783 回答
0

您可以使用基于数组的断言。为此,您必须将枚举转换为数组。

Object[] enumAsArray = Collections.list(objList).toArray();

于 2012-09-14T09:44:40.180 回答