问题
Using JUnit 4.12 and AndroidStudio I am trying to test below method Where results seems to be matching I don't know why as a reesult I am getting
java.lang.AssertionError
Method under test:
public String dateNow() {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy_hh-mm-ss");
String date = sdf.format(new Date());
return date;
}
My test class :
private Addons mAddons;
@Before
public void setUp() throws Exception{
mAddons = new Addons();
}
@Test
public void testDateNow() throws Exception {
final String reality = mAddons.dateNow().substring(0,10);
final String expected = "09-08-2017";
assertSame("testDateNow() :", expected, reality);
}
console output:
java.lang.AssertionError: testDateNow() : expected same:<09-08-2017> was not:<09-08-2017>
Expected :09-08-2017
Actual :09-08-2017
I don't know why it is failing. Anyone would bee so king to point me into right direction please?
回答1:
assertSame checks if the two parameters are the same object. And they aren't.
If you want to check if they have the same content, you should use assertEquals instead.
回答2:
The toString() methods of the two dates are printing the same thing, but the objects they are referring to might be different.
回答3:
While your logic is correct, you are using the wrong assertion in your test. The documentation for assertSame says that it asserts the two object must refer to the same object. This means that the two objects must be refering to the same object.
When you assign reality
to the string "09-08-2017"
, the variable reality
is now refering to an object containing the value "09-08-2017"
in the memory.
The mAddons.dateNow().substring(0,10)
generates another object, with the same value "09-08-2017"
, so expected
has the same value, but it's not refer to the same object in the memory.
To assert that the values is the same, you should use assertEquals which will test for value equality, not reference.
This is a very common mistake when comparing strings in Java.
I suggest you also to read the follow article: Java String compare
来源:https://stackoverflow.com/questions/45592405/junit-assertionerror-when-testing-simpledateformat