How to make Weld lookup class on generated-sources

893 views Asked by At

I have a maven project which i'm using MapStruct to generate mappers to help in the job of translating entities into DTOs and vice-versa. This mappers are generated during the generate-sources phase of maven, and stored into target/generated-sources and target/AppName/WEB-INF/classes folders.

For example, I have this Mapper

@Mapper
public interface RuleMapper {

    RuleDto ruletoDto(Rule rule);

    //other cool stuf
}

I configurated MapStruct to use CDI, so it will generate the following:

@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2016-12-19T23:19:36-0200",
comments = "version: 1.1.0.CR1, compiler: javac, environment: Java 1.8.0_112"
)
@Singleton
@Named
public class RuleMapperImpl implements RuleMapper {

    @Override
    public RuleDto ruletoDto(Rule rule) {

        ruleDto ruleDto = new ruleDto();

        if ( rule != null ) {
            ruleDto.setIdRule( rule.getIdRule() );
        }

        return ruleDto;
    }
}

It works perfectely when running on Wildfly server, the problem is that I'm trying to junit test this class, for this, I implemented a custom runner as shown bellow:

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

public class WeldJUnit4Runner extends BlockJUnit4ClassRunner {

    public WeldJUnit4Runner(Class<Object> clazz) throws InitializationError {
        super(clazz);
    }

    @Override
    protected Object createTest() throws Exception {
        final Class<?> test = getTestClass().getJavaClass();
        return WeldContext.INSTANCE.getBean(test);
    }

}

And:

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

public class WeldContext {

    public static final WeldContext INSTANCE = new WeldContext();

    private final Weld weld;
    private final WeldContainer container;

    private WeldContext() {
        this.weld = new Weld();
        this.container = weld.initialize();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                weld.shutdown();
            }
        });
    }

    public <T> T getBean(Class<T> type) {
        return container.instance().select(type).get();
    }

}

These implementations were taken from here.

Finally, the test:

@RunWith(WeldJUnit4Runner.class)
public class RuleMapperTest {

    @Inject
    private RuleMapper ruleMapper;

    @Test
    public void coolTestName() {
        Assert.assertTrue(Boolean.TRUE);
    }
}

When I try to run, this is the console output:

log4j:WARN No appenders could be found for logger (org.jboss.logging). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

warning about logs, and the following exception:

java.lang.ExceptionInInitializerError at br.com.treinoos.common.cdi.WeldJUnit4Runner.createTest(WeldJUnit4Runner.java:15) at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type RuleMapper with qualifiers @Default at injection point [BackedAnnotatedField] @Inject private br.com.treinoos.model.core.business.treinoos.mappers.RuleMapperTest.ruleMapper at br.com.treinoos.model.core.business.treinoos.mappers.RuleMapperTest.ruleMapper(RuleMapperTest.java:0) at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:359) at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:281) at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134) at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:155) at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:518) at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:68) at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:66) at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:63) at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:56) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745)

Like Weld wasn't abble to lookup the generated class. The beans.xml is already created under src/test/resources/META-INF/beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
                  http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
    version="1.1" bean-discovery-mode="all">
</beans>

Can anybody point me a solution to this problem? I've already searched something simillar, but no success.

1

There are 1 answers

1
John Ament On BEST ANSWER

Here's a full explanation to your problem and why what I wrote fixes it.

In Maven, you have at least 2 classloader. Your test classpath and your main classpath each have their own classloader. You can have others depending on your dependency structure. CDI identifies each classloader as a separate bean archive when running this way. src/main/webapp is explicitly for your WAR file. The beans.xml there does not give you a bean archive. Adding one to src/main/resources does. This problem is specific to how you're instantiating weld.

There are other projects that do this correctly - CDI-unit and Arquillian, specifically the Weld Embedded container. If you were to use one of these, this would not be an issue.