9

My code is like below

@Test public void testMyMethod(){ MyClass mc = new MyClass(); String exeVal="sometext some text"; String x=mc.exampleMethod(); // Assertion type 1 Assert.assertEquals(exeVal,x); //Assertion Type 2 Assert.assertTrue(exeVal.equals(x)); } 

I want to know which is the best approach.

3
  • 1
    It's the same. assertEquals() invokes the equals() method on given objects. Use whatever you prefer. Commented Jul 18, 2014 at 9:47
  • 2
    Based solely on readability I would go for assertEquals(). Commented Jul 18, 2014 at 9:49
  • 1
    @BartekMaraszek As assertEquals will give you clearer feedback, I'd say it is better to use that. Commented Jul 18, 2014 at 9:49

2 Answers 2

19

Type 1 is preferred because of the assertion message you will receive when they do not match.

org.junit.ComparisonFailure: expected: <[foo]> but was: <[bar]> 

vs

java.lang.AssertionError 
Sign up to request clarification or add additional context in comments.

Comments

0

Type 1 is preferred because of the following reasons.

  • It gives you a better error message.

ex:- "expected [3] but found [4]" . The second approach will evaluate the condition and will give you a message like "expected [true] but found [false]" and the user will not get the values evaluated.

  • AssertEquals is null safe and assertTrue isn't

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.