tags:

views:

82

answers:

5
+1  Q: 

Junit test methods

What are the most oftenly used test methods I should start with in order to get familiar with unit testing? There are just a lot of them, but I guess there are some like common or something.

I meant Junit methods like AssertTrue(), etc.

+1  A: 

setUp() and tearDown(), they are called before and after each case.

Jes
+3  A: 

assertEquals is the most commonly used test method.

assertEquals( "string1", "string1" ); 
//would fail

assertEquals( expectedValue, actualValue ); 
//would pass if expectedValue.equals( actualValue )

You can also add a comment that is printed if the assertion fails:

assertEquals( "method result should be 7", 7, thing.methodThatShouldReturn7() );
//would pass if 7 == thing.methodThatShouldReturn7()

See the Assert class javadoc for more details and once you are comfortable with assertEquals, you can look at the other assert options available to you.

Alex B
You really want to use the latter method that gives you an error string; it'll help when things go wrong. Also note how the message is worded, as an expectation rather than telling some wrong value. That way of wording helps a lot in figuring out what happened
Paul Rubel
+3  A: 

There are just a few patterns to learn, with multiple implementing methods for different types and an optional initial message argument.

  • assertEquals()
  • assertTrue() and assertFalse()
  • assertNull() and assertNotNull()
  • assertSame() and assertNotSame()
  • fail()
  • assertArrayEquals()
  • assertThat()

At a minimum you'll need to learn all the patterns but the last -- these are all needed for different situations.

Andy Thomas-Cramer
+1  A: 

I would also recommend knowing about fail() and exception handling within JUnit. The brief suggestion is to always throw exceptions from the test method unless testing for that specific exception. Catching exceptions and failing works, but you lose quite a bit of information on reports. A good article about it is here: http://www.exubero.com/junit/antipatterns.html.

Dante617
A: 

@Before and @After annotations (equivalent to what setUp() and tearDown() are for).

AHungerArtist