可以强制吗
assertEquals("10,00 €", new Currency(bon.getTotal()))
使用货币对象的toString()方法? (我不想自己称呼它。)
否则,它会比较参考文献,这当然不匹配。
java.lang.断言错误:
预期:java.lang.String<10,00 €>
但是是: jam.cashregister.Currency<10,00 €>
更新
我最终得到了这段代码:
assertEquals(new Currency(bon.getTotal()), "10,00 €");
我不知道将预期与 断言中的实际部分。
public class Currency() {
@Override
public boolean equals(Object other) {
return this.toString().equals(other.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());
我也有同样的错误。 我用了这个方法。
assertEquals(20 , new Duller(result.multiple()).toString());
不起作用。
public class MoneyTest {
@Test
public void testMultiplication(){
Duller fiveValue= new Duller(5);
Duller twoTimes = fiveValue.times(2);
assertEquals(10,twoTimes.amount);
Duller threeTimes = fiveValue.times(3);
assertEquals(15, threeTimes.amount);
Duller result = new Duller();
result.setAmount(4);
result.setTimes(5);
int x= result.multiple();
/*
org.opentest4j.AssertionFailedError:
Expected :20
Actual :com.bahar.test.domain.Duller@16aa0a0a
*/
// assertEquals(20 , new Duller(result.multiple(result.getTimes())); //actual and expected is obj
assertEquals(20,x);
}
}
public class Duller {
int amount;
int times;
public Duller(){}
public Duller(int amount){
this.amount=amount;
}
Duller times(int multiple){
// amount *=multiple; // version 1
return new Duller(amount*multiple); //version 2
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getTimes() {
return times;
}
public void setTimes(int times) {
this.times = times;
}
// changed the Dullar to int
public int multiple(){
// amount *=multiple; // version 1
return getAmount()*getTimes(); //version 2
// return this.getAmount()*this.getTimes();
}