Search code examples
java-8cdijunit4cdi-unit

CDI, cdi-unit. Exception trying inject interface


I test class using cdi-unit library. Test class:

@RunWith(CdiRunner.class)
public class IAktResponseMapperTest {
    @Inject
    private ITestCDI testCDI;

    @Test
    public void testCDI(){
        testCDI.testCDI();
    }
}

ITestCDI interface:

public interface ITestCDI {
    void testCDI();
}

TestCDI class:

@ApplicationScoped
public class TestCDI implements ITestCDI {
    public void testCDI() {
        System.out.println("testCDI");
    }
}

So, running this test I get error:

org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type ITestCDI with qualifiers @Default
  at injection point [UnbackedAnnotatedField] @Inject private ru.nwth.pio.personal_area.accounting.mapper.IAktResponseMapperTest.testCDI
  at ru.nwth.pio.personal_area.accounting.mapper.IAktResponseMapperTest.testCDI(IAktResponseMapperTest.java:0)

But if I inject TestCDI class directly instead of interface ITestCDI, it's ok. How can I make interface working? Thanks for help!


Solution

  • CDI-Unit does not scan all classes of your package, so does not know the TestCDI implementation of ITestCDI. You can control CDI environment with CDI-Unit using @AdditionalClasses, @AdditionalPackages or @AdditionalClasspath annotation.

    In your case, add for example @AdditionalClasses(TestCDI.class) annotation :

    @RunWith(CdiRunner.class)
    @AdditionalClasses(TestCDI.class) 
    public class IAktResponseMapperTest {
        @Inject
        private ITestCDI testCDI;
    
        @Test
        public void testCDI(){
            testCDI.testCDI();
        }
    }