【问题标题】:overriding toString() representation of object returns unexpected symbol覆盖对象的 toString() 表示返回意外符号
【发布时间】:2012-11-02 00:52:47
【问题描述】:

我正在为 Clock 类编写 JUnit 测试方法,以确保对象的 toString 表示以我想要的格式返回。所以,我已经覆盖了 toString() 并按照它想要的方式编写它,但是当我将它与我期望在 JUnit 中的格式进行比较时,它会失败并显示以下内容:

org.junit.ComparisonFailure: 预期: 但是:

为什么这里显示符号 [ 和 ]?它是我不知道的 toString() 表示的一部分吗?相关代码如下:

JUnit:

    @Test
public void testFormattingOfTimeIsDisplayedCorrectly() {

    final byte TEN = 10;
    final byte DBL_ZERO = 00;

    clock.setTime(TEN, DBL_ZERO, DBL_ZERO);

    final String EXPECTED_STRING = "Time : 10:00:00";

    assertEquals(EXPECTED_STRING, clock.toString());    

}

时钟类中的toString():

@Override
public String toString() {
    return "Time : " + hours + ":" + minutes + ":" + seconds;
}

setTime 方法也在 Clock 类中:

public void setTime(byte hour, byte minutes, byte seconds) {

    this.hours = hour;
    this.minutes = minutes;
    this.seconds = seconds;

}

我想知道,也许它与使用字节有关?或者它只是我不明白的 toString() 返回的东西。我只是对为什么我的 JUnit 方法不将它们视为相同的格式感到困惑。

【问题讨论】:

  • [ ] 符号仅用于断言输出(:

标签: java junit junit4 tostring primitive-types


【解决方案1】:

这个:

<10:0[0:0]0 > but was:< Time : 10:0[:]0>

表示差异。即输出是 10:0:0 而不是 10:00:00。考虑到您的代码是这样做的,这并不奇怪:

return "Time : " + hours + ":" + minutes + ":" + seconds;

分钟/秒不是零填充的。或许可以使用%02d 格式设置查看String.format()。我不明白(也)为什么你会使用 byte 作为值。 int 将是在这里使用的更正常的类型。

【讨论】:

  • 啊,我明白了。我刚刚将 EXPECTED_STRING 更改为: final String EXPECTED_STRING = "Time : 10:0:0";并且测试通过了。但我想要填充零,所以我会按照你的建议检查 String.format() 。谢谢
【解决方案2】:

按行替换:

return "Time : " + String.format("%02d", hours) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds);

【讨论】:

  • 为什么不return String.format("Time : %02d:%02d:%02d", hours, minutes, seconds)
【解决方案3】:

指出您的方法返回 10:0:0 而不是 10:00:00。数值类型不存储前导零,因此您的 DBL_ZERO 常量无法按您想要的方式工作。

试试这个:

@Override
public String toString() {
    return "Time : " + hours + ":"
        + (minutes < 10 ? "0" : "") + minutes + ":"
        + (seconds < 10 ? "0" : "") + seconds;
}

【讨论】:

    猜你喜欢
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多