Tutorial by Examples

Since JUnit is a Java library, all you have to do to install it is to add a few JAR files into the classpath of your Java project and you're ready to go. You can download these two JAR files manually: junit.jar & hamcrest-core.jar. If you're using Maven, you can simply add in a dependency into...
This example is a basic setup for unittesting the StringBuilder.toString() using junit. import static org.junit.Assert.assertEquals; import org.junit.Test; public class StringBuilderTest { @Test public void stringBuilderAppendShouldConcatinate() { StringBuilder stringBui...
An annotated method with @Before will be executed before every execution of @Test methods. Analogous an @After annotated method gets executed after every @Test method. This can be used to repeatedly set up a Test setting and clean up after every test. So the tests are independent and preparation cod...
It is possible to easily catch the exception without any try catch block. public class ListTest { private final List<Object> list = new ArrayList<>(); @Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { list.get(0); } } ...
To ignore a test, simply add the @Ignore annotation to the test and optionally provide a parameter to the annotation with the reason. @Ignore("Calculator add not implemented yet.") @Test public void testPlus() { assertEquals(5, calculator.add(2,3)); } Compared to commenting the...
Here’re some basic JUnit annotations you should understand: @BeforeClass – Run once before any of the test methods in the class, public static void @AfterClass – Run once after all the tests in the class has been run, public static void @Before – Run before @Test, public void @After – Run after...

Page 1 of 1