tug*_*cem 6 java junit hamcrest
我有相当复杂的对象结构(有一堆原始字段和对象引用),并且想要测试除了少数几个字段之外的所有字段.举个例子;
ComplexObject actual = generateMagically("someInput");
ComplexObject expected = ActualFunction.instance.workMagically(actual);
// we want to be sure that workMagically() would create a new ComplexObject
// with some fields are different than "actual" object.
// assertThat(actual, samePropertyValuesAs(expected)); would check all fields.
// what I want is actually; - notice that "fieldName1" and "fieldName2" are
// primitives belong to ComplexObject
assertThat(actual, samePropertyValuesExceptAs(expected, "fieldName1", "fieldName2"))
Run Code Online (Sandbox Code Playgroud)
由于我不想手动检查所有字段,我相信必须有一种方法来优雅地编写该测试.有任何想法吗?
干杯.
你应该看看shazamcrest,这是一个很棒的Hamcrest扩展,提供你需要的东西.
assertThat(expected, sameBeanAs(expectedPerson).ignoring("fieldName1").ignoring("fieldName2"));
Run Code Online (Sandbox Code Playgroud)
请参阅https://github.com/shazam/shazamcrest#ignoring-fields
只需将要忽略的属性列表作为第二个参数传递给 samePropertyValuesAs 即可。
Hamcrest 匹配器 API
public static <B> Matcher<B> samePropertyValuesAs(B expectedBean, String... ignoredProperties)
Run Code Online (Sandbox Code Playgroud)
例如
samePropertyValuesAs(salesRecord,"id")
Run Code Online (Sandbox Code Playgroud)
一般来说,我看到两种解决方案,如果ComplexObject可以自己修改的话。
ComplexObject您可以引入一个接口来表示正在更改的属性ActualFunction。然后您可以测试该新接口的所有属性是否已更改。这将需要ComplexObject实现该新接口。
另一种方法是用包含所有这些属性的新类型的新属性ComplextObject来替换已更改的属性。ActualFunction更好的设计是返回ActualFunction新类型的实例。
| 归档时间: |
|
| 查看次数: |
5022 次 |
| 最近记录: |