在整理演示文稿时,我遇到了一种情况,我预计会出现异常,但是当我运行相应的单元测试时却什么也没有。我正在做的是增量修改一个bean。在这个版本的Product
andAccessory
类中,我删除了所有属性的 setter/getter(除了 Product 属性之一的 setter)。我之前已将我的类转换为使用字段访问表示法。所以,由于我已经删除了 setter/getter,我期待一个例外,因为字段可见性修饰符是私有的。
这是附件类:
public class Accessory {
private String name
private BigDecimal cost
private BigDecimal price
public Accessory() {
this.cost = BigDecimal.ZERO
this.price = BigDecimal.ZERO
}
public Accessory(String name, BigDecimal cost, BigDecimal price) {
this.name = name
this.cost = cost
this.price = price
}
@Override
public int hashCode() {
final int prime = 31
int result = 1
result = prime * result + ((cost == null) ? 0 : cost.hashCode())
result = prime * result + ((name == null) ? 0 : name.hashCode())
result = prime * result + ((price == null) ? 0 : price.hashCode())
return result
}
public boolean equals(Accessory obj) {
return name == obj.name &&
cost == obj.cost &&
price == obj.price
}
@Override
public String toString() {
return "Accessory [" + "name=" + name + ", cost=" + cost + ", price=" + price + "]"
}
}
以下是 Product 类的片段:
public class Product {
private String model
private List<Accessory> accessories
private TreeMap<Integer, BigDecimal> priceBreaks
private BigDecimal cost
private BigDecimal price
...
public BigDecimal getAccessorizedCost() {
...
for (Accessory pkg : this.accessories) {
pkgCost = pkgCost.add pkg.cost
}
return pkgCost
}
...
}
我希望pkgCost = pkgCost.add pkg.cost
上面代码段中的行会引发异常。同样,我认为我的单元测试中的以下断言会做同样的事情:
@Test public void canCreateDefaultInstance() {
assertNull "Default construction of class ${defaultProduct.class.name} failed to properly initialize model.", defaultProduct.model
assertTrue "Default construction of class ${defaultProduct.class.name} failed to properly initialize accessories.", defaultProduct.accessories.isEmpty()
assertTrue "Default construction of class ${defaultProduct.class.name} failed to properly initialize priceBreaks.", defaultProduct.priceBreaks.isEmpty()
assertEquals "Default construction of class ${defaultProduct.class.name} failed to properly initialize cost.", BigDecimal.ZERO, defaultProduct.cost as BigDecimal
assertEquals "Default construction of class ${defaultProduct.class.name} failed to properly initialize price.", BigDecimal.ZERO, defaultProduct.price as BigDecimal
}
以下是元类属性和方法:
MetaClass Properties are:
[accessorizedCost, accessorizedPrice, class, priceBreaks]
MetaClass Methods are:
[__$swapInit, addPriceBreak, calcDiscountMultiplierFor, calcVolumePriceFor, equals, getAccessorizedCost, getAccessorizedPrice, getClass, getMetaClass, getProperty, hashCode, invokeMethod, notify, notifyAll, setMetaClass, setPriceBreaks, setProperty, toString, wait]
例如,您可以看到私有定义model
的accessories
、cost
和price
字段没有属性,也没有相应的 getter/setter。因此,就像 Product 类中的行在引用 Accessory 的成本属性时没有失败一样,我不明白当这些私有字段没有属性或 getter/setter 时单元测试如何通过。
我正在使用 Groovy 2.0.4 编译并运行 Eclipse。
我错过了什么或不理解什么?