在 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 要求我添加我的 GpsCooperatives.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";
}
最佳答案
预期值没有“\n”,而 GpsCooperative.toString() 添加了它。
关于java - JUnit 比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35306775/