在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";
}
答案 0 :(得分:4)
GpsCoordinate.toString()添加时,预期值没有“\ n”。
答案 1 :(得分:1)
因此可能导致此问题的一件事是意外的尾随空格。
你有几个方法可以解决这个问题:
在eclipse或类似的IDE中运行可以让您通过双击失败来获取更多信息。在eclipse中,你得到了assertEquals
失败的两个字符串的差异 - 这显示了显而易见的差异。
在比较之前将句子添加到字符串中:例如
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
'
问题很明显。