junit 强制assertEquals(String s,Object o)使用o.toString()?

vqlkdk9b  于 2023-10-20  发布在  其他
关注(0)|答案(3)|浏览(89)

有没有可能强迫

assertEquals("10,00 €", new Currency(bon.getTotal()))

使用Currency Object的toString()方法?(我不想自己叫它)。
否则,它会比较引用,当然不匹配。
java.lang.AssertionError:
expected:java.lang.String<10,00 €>
但是:果酱.收银机.货币<10,00 €>

更新

最后我得到了这样的代码:

assertEquals(new Currency(bon.getTotal()), "10,00 €");

我不知道在Assert中,把期望的部分和实际的部分交换是不是一个好主意。

public class Currency() {

    @Override
    public boolean equals(Object other) {
        return this.toString().equals(other.toString());
    }
}
vnjpjtjt

vnjpjtjt1#

您应该比较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;
    }

    ...
}
j9per5c4

j9per5c42#

不,唯一的方法就是自己写:

assertEquals("10,00 €", new Currency(bon.getTotal()).toString());
pzfprimi

pzfprimi3#

我也犯了同样的错误。我采用了这种方法。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();

    }

相关问题