Weld JUnit 4 Runner

I’ve been having a look at Weld recently and wanted to be able to try some stuff out without a container in JUnit, but couldn’t find a JUnit Runner class to do it for me.

I was really suprised how simple it was:

package org.objectopia.test;

import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;

import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;

public class WeldJUnit4Runner extends BlockJUnit4ClassRunner {

    private final Class klass;
    private final Weld weld;
    private final WeldContainer container;

    public WeldJUnit4Runner(final Class klass) throws InitializationError {
        this.klass = klass;
        this.weld = new Weld();
        this.container = weld.initialize();

    protected Object createTest() throws Exception {
        final Object test = container.instance().select(klass).get();

        return test;

Now you can do this :

public class PersistenceTest {

    @Inject UserRepository repository;


Because your test class is just another CDI bean, you can inject any bean reference you require.

This is where the power of CDI comes in to play, you can do something like this:

    @Inject @Mock UserRepository userRepository;

And create a producer method to mock it out:

    @Produces @Mock UserRepository createUserRepository() { ... }

EJB 3.0 Injecting The Correct Implementation

When using stateless and stateful session beans I often find that I’m creating one interface per one implementation, which will be enhanced with the release of the 3.1 spec and implicit interfaces. Anyway on one of the occasions I had actually had multiple implementations of an interface that I wanted to inject, this made me stop and think how do I that!! It turns out it was pretty simple with a few annotations.

On your class that is implementing the interface you need to use the name attribute: –

public class AssetTypeOverrideService implements OverrideService{

public class RuleTypeOverrideService implements OverrideService {

Then on the bean you want inject these into you use:

private OverrideService assetOverrideService;
private OverrideService ruleTypeOverrideService;

The name can be anything you want I just think it’s logical to keep it the same as the class and the beanName obviously is the same value of the bean you want to inject that has the correct implementation.

It seems easy now but it did make me stop and think.