I'm confusing about both these methods, because both can do the same thing, like below snippet of my code.
Using assertEquals()
String a = "Hello";
String b = "Hello";
assertEquals(a, b);
Using assertTrue()
assertTrue(a.equals(b));
Can anyone tell me the actual difference between both these two methods?
assertEquals() Asserts that two objects are equal. assertSame() Asserts that two objects refer to the same object. the assertEquals should pass and assertSame should fail, as the value of both classes are equal but they have different reference location.
assertTrue(condition) : This method asserts if the condition is true or not. If not, then the exception error is thrown. Assert. assertTrue(condition, message) : Similar to the previous method with an addition of message, which is shown on the console when the assertion fails along with the exception.
Assert: If the assert condition is true then the program control will execute the next test step but if the condition is false, the execution will stop and further test step will not be executed. whereas, Verify: There won't be any halt in the test execution even though the verify condition is true or false.
assertEquals. Asserts that two objects are equal. If they are not, an AssertionError without a message is thrown. If expected and actual are null , they are considered equal.
assertEquals
is better because it gives the unit test framework more information about what you're actually interested in. That allows it to provide better error information when the test fails.
Suppose you had
String a = "Hello";
String b = "Hi";
Then the test failures might look something like:
// From assertEquals(a, b)
Error: Expected "Hi"; was "Hello"
// From assertTrue:
Error: Expected true; was false
Which of those do you think gives you more information, bearing in mind that the values would probably be the result of reasonably complex computations?
(These are made up error messages as I don't have testng installed, but they're the kind of thing unit test frameworks give.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With