强制 assertEquals(String s, Object o) 使用 o.toString()?
force assertEquals(String s, Object o) to use o.toString()?
是否可以强制
assertEquals("10,00 €", new Currency(bon.getTotal()))
使用货币对象的 toString() 方法?
(我不想自己叫它。)
否则,它会比较引用,当然不匹配。
java.lang.AssertionError:
expected: java.lang.String<10,00 €>
but was: jam.cashregister.Currency<10,00 €>
更新
我终于得到了这段代码:
assertEquals(new Currency(bon.getTotal()), "10,00 €");
I don't know if it is a good idea to swap the expected with
the actual part, in the assertation.
public class Currency() {
@Override
public boolean equals(Object other) {
return this.toString().equals(other.toString());
}
}
不行,唯一的办法就是自己写:
assertEquals("10,00 €", new Currency(bon.getTotal()).toString());
您应该比较 Currency
的两个实例:
assertEquals(new Currency("10,00 €"), new Currency(bon.getTotal()))
因此,必须重新定义 equals()
。如果相等性必须基于 Currency
的字符串表示形式,则还必须覆盖 toString()
(您可能已经这样做了)。
public class Currency {
...
@Override
public String toString() {
//overriden in a custom way
}
@Override
public boolean equals(Object other) {
if(other instanceof Currency) {
Currency that = (Currency) other;
return this.toString().equals(that.toString());
}
return false;
}
...
}
是否可以强制
assertEquals("10,00 €", new Currency(bon.getTotal()))
使用货币对象的 toString() 方法? (我不想自己叫它。)
否则,它会比较引用,当然不匹配。
java.lang.AssertionError:
expected: java.lang.String<10,00 €>
but was: jam.cashregister.Currency<10,00 €>
更新
我终于得到了这段代码:
assertEquals(new Currency(bon.getTotal()), "10,00 €");
I don't know if it is a good idea to swap the expected with the actual part, in the assertation.
public class Currency() {
@Override
public boolean equals(Object other) {
return this.toString().equals(other.toString());
}
}
不行,唯一的办法就是自己写:
assertEquals("10,00 €", new Currency(bon.getTotal()).toString());
您应该比较 Currency
的两个实例:
assertEquals(new Currency("10,00 €"), new Currency(bon.getTotal()))
因此,必须重新定义 equals()
。如果相等性必须基于 Currency
的字符串表示形式,则还必须覆盖 toString()
(您可能已经这样做了)。
public class Currency {
...
@Override
public String toString() {
//overriden in a custom way
}
@Override
public boolean equals(Object other) {
if(other instanceof Currency) {
Currency that = (Currency) other;
return this.toString().equals(that.toString());
}
return false;
}
...
}