【问题标题】:JUnit Comparing StringsJUnit比较字符串
【发布时间】:2016-02-10 04:19:46
【问题描述】:

在 JUnit 上做一些功课。我们必须测试我们所有的方法。我已经写出了其他 4 种方法并正确测试,但是我遇到了 toString 方法无法正常工作的问题。

//here is my Gps constructor, if needed. I don't think it is, but including it just in case.

public Gps(String n, GpsCoordinates pos)
    {
        super();
        this.name = n;
        this.position = pos;
    }

//Here is my Gps.class toString() method that I want to test.
@Override
public String toString()
    {
        String gps = "myGPS: " + name + ": " + position;
        return gps;
    }

这是我的 JUnit 测试方法:

//Here are my instances in my GpsTest.class

private GpsCoordinates testGpsCoordinates = new GpsCoordinates(40.760671, -111.891122);
private Gps testGps3 = new Gps("TEST3", testGpsCoordinates);

//Here is my toString test method
    @Test
    public void testToString()
        {
            String expected = "myGPS: TEST3: 40.760671, -111.891122";
            assertEquals(expected, testGps3.toString());
        }

所以当我运行它时,我得到了一个 JUnit 失败。我检查了日志,它说:

Expected:
myGPS: TEST3: 40.760671, -111.891122

Actual:
myGPS: TEST3: 40.760671, -111.891122

我认为 assertEquals 可能使用“==”而不是 .equals(),但事实并非如此——它确实使用 .equals(),所以我没有想法

谁能指出我正确的方向?我已经搞砸了 30 分钟,在我的实例中移动、重命名等等,并且正在拉扯我的头发。

cricket_007 要求我添加我的 GpsCoordinates.toString(),这里是:

public String toString()
{
    //formatting this to only return to 6 decimal places. On a separate part
    //of the assignment, we are to add a random double to the GpsCoordinates
    //(like a fake "gps update") and limit it to 6 decimal places.
    DecimalFormat df = new DecimalFormat("####.000000");
    return df.format(latitude) + ", " + df.format(longitude) + "\n";
}

【问题讨论】:

  • GpsCoordinates.toString好吗?
  • @cricket_007 我将其添加到原始帖子中。你认为我的 GpsCoordinates.toString() 被调用而不是 Gps.toString() 吗?
  • 与位置变量进行字符串连接时调用。这就是我问的原因。
  • @cricket_007 你是对的,我很笨。 “位置”属于 GpsCoordinates,而不是 Gps。谢谢板球!
  • 是的,你在预期的末尾缺少了一个新行

标签: java junit


【解决方案1】:

GpsCoordinate.toString() 添加时,预期值没有“\n”。

【讨论】:

    【解决方案2】:

    因此,可能导致此问题的一件事是意外的尾随空格。

    你有几个选择来处理这个问题:

    1. 在 Eclipse 或类似 IDE 中运行可能会让您选择通过双击失败来获取更多信息。在 Eclipse 中,您会得到 assertEquals 失败的两个字符串的差异 - 这以明显的方式显示了差异。

    2. 在比较之前将哨兵添加到您的字符串中:例如

      assertEquals("'myGPS: TEST3: 40.760671, -111.891122'",
                   "'" + testGps3.toString() +"'")
      

      任何空白差异现在应该更加明显。

    正如 Mateusz Mrozewski 所说,您的输出中有一个额外的换行符。在这种情况下,2. 的输出将是

    Expected:
    'myGPS: TEST3: 40.760671, -111.891122'
    
    Actual:
    'myGPS: TEST3: 40.760671, -111.891122
    '
    

    问题很明显。

    【讨论】:

    • 我实际上正在寻找一种方法来做到这一点,所以我将来肯定会使用它。谢谢迈克尔。
    猜你喜欢
    • 2018-10-16
    • 2011-05-13
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    相关资源
    最近更新 更多