Reputation: 61
Doing some homework on JUnit. We have to test all our methods. I have the other 4 methods wrote out and testing correctly, but I am having trouble with the toString method not working like it should.
//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;
}
Here is my JUnit test method:
//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());
}
So when I run this, I get a JUnit failure. I check the logs and it says:
Expected:
myGPS: TEST3: 40.760671, -111.891122
Actual:
myGPS: TEST3: 40.760671, -111.891122
I thought maybe assertEquals uses "==" instead of .equals(), but that was not the case -- it DOES use .equals(), so I'm out of ideas
Can anyone point me in the right direction? I have been messing with this for 30 minutes now, moving around my instances, renaming things, etc. and am pulling my hair out.
cricket_007 asked that I add my GpsCoordinates.toString(), here it is:
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";
}
Upvotes: 0
Views: 3064
Reputation: 73470
So one thing that can cause this problem is unexpected trailing whitespace.
You've got a couple of options to handle that:
Running in eclipse or similar IDE may give you the option to get more information by double clicking on the failure. In eclipse you get a diff of the two strings for assertEquals
failures - which shows the difference in a obvious way.
Add sentries to your strings before comparing: e.g.
assertEquals("'myGPS: TEST3: 40.760671, -111.891122'",
"'" + testGps3.toString() +"'")
Any white-space differences should now be more obvious.
As Mateusz Mrozewski mentions you have an extra newline in your output. In this case the output for 2. will be
Expected:
'myGPS: TEST3: 40.760671, -111.891122'
Actual:
'myGPS: TEST3: 40.760671, -111.891122
'
And the issue is obvious.
Upvotes: 2
Reputation: 2191
Expected value does not have "\n" while GpsCoordinate.toString() adds it.
Upvotes: 4