Child pages
  • Getting Started with CDI Tests
Skip to end of metadata
Go to start of metadata

Writing a test

Write a JUnit test using any of the usual JUnit 4.x annotations and use @Inject in combination with appropriate qualifiers to inject the beans under test.

Example:

@RunWith( PaxExam.class )
public class VanillaTest
{
    @Inject
    @Vanilla
    private IceCreamService vanilla;

    @Inject
    @Chocolate
    private IceCreamService chocolate;

    @Inject
    private IceCreamService defaultFlavour;

    @Test
    public void checkVanillaFlavour()
    {
        assertThat( vanilla.getFlavour(), is( "Vanilla" ) );
    }

    @Test
    public void checkChocolateFlavour()
    {
        assertThat( chocolate.getFlavour(), is( "Chocolate" ) );
    }

    @Test
    public void checkDefaultFlavour()
    {
        assertThat( defaultFlavour.getFlavour(), is( "Vanilla" ) );
    }
}

In this example, IceCreamService is an interface implemented by two managed beans VanillaService, qualified by @Vanilla @Default, and ChocolateService, qualified by @Chocolate.

When running this test with Pax Exam, the PaxExam JUnit runner starts a CDI container embedded in the current Java VM and uses the BeanManager to inject dependencies into instances of JUnit test classes instantiated by JUnit (i.e. not managed by the CDI container). When all dependencies are satisfied, all test methods are executed directly by the JUnit driver.

All of this is completely transparent to the outer JUnit runner (e.g. the JUnit launcher of Eclipse, or the Surefire Maven plugin).

Thus, working with Eclipse, you can easily run a whole set of Pax Exam tests by simply selecting a Java package with test classes and then launching JUnit from the context menu.

Running a Test

  • Make sure that all dependencies of your system under test and all required Pax Exam modules are on the classpath (see Maven Dependencies).
  • Create a configuration file exam.properties in the root of your classpath with the following contents:

    pax.exam.system = cdi
    
  • Run your test or a whole set of tests just like any plain old JUnit test, e.g. from your IDE, under Maven Surefire or as part of your Continuous Integration job.

Supported Containers

Read more about the supported CDI Containers.

  • No labels