junit

Topics related to junit:

Getting started with junit

JUnit is a simple framework to write repeatable tests for Java programming language. It is an instance of the xUnit architecture for unit testing frameworks.

Main features consist of:

  • Assertions, that let you customize how to test values in your tests
  • Test runners, that let you specify how to run the tests in your class
  • Rules, that allow you to flexibly modify the behaviour of tests in your class
  • Suites, that allow you to build together a suite of tests from many different classes

Useful extension for JUnit:

  • AssertJ: Fluent assertions for java
  • Mockito: Mocking framework for java

Tests

ParameterContextDetails
@BeforeClassStaticExecuted when the class is first created
@BeforeInstanceExecuted before each test in the class
@TestInstanceShould be declared each method to test
@AfterInstanceExecuted after each test in the class
@AfterClassStaticExecuted before destruction of the class

Example Test Class Format

public class TestFeatureA {

    @BeforeClass
    public static void setupClass() {}
    
    @Before
    public void setupTest() {}
    
    @Test
    public void testA() {}
    
    @Test
    public void testB() {}
    
    @After
    public void tearDownTest() {}
    
    @AfterClass
    public static void tearDownClass() {}
    
    }
}

Test Execution Order

Testing with DataProviders

Ignore test cases in Junit

Generate Junit test cases skeleton for existing code

Paramaterizing Tests

One benefit to using parameters is that if one set of data fails, execution will just move to the next set of data instead of stopping the whole test.

Custom Test Rules

There are benefits for either. Extending ExternalResource it's convenient, especially if we only require a before() to set something up.

However, we should be aware that, since the before() method is executed outside of the try...finally, any code that is required to do clean up in after() won't get executed if there is an error during the execution of before().

This is how it looks inside ExternalResource:

before();
try {
    base.evaluate();
} finally {
    after();
}

Obviously, if any exception is thrown in the test itself, or by another nested rule, the after will still get executed.