【发布时间】: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。谢谢板球!
-
是的,你在预期的末尾缺少了一个新行