简体   繁体   中英

Java CDI @Inject throws NullPointerException

I'm testing the Java 7 CDI features following the official documentation but I'm getting a NullPointerException when I try to access the greeting object. The project if a Jar Maven one.

This is the Greeting class

package greetings;

import javax.enterprise.inject.Default;
@Default
public class Greeting {
    public void  greet(String name) {
        System.out.println("Hello, " + name + ".");
    }
}

This is the test class where I'm injecting the bean

package greetings;

import static org.junit.Assert.assertTrue;
import javax.inject.Inject;
import org.junit.Test;

public class Tester {

    @Inject Greeting greeting;

    @Test
    public void greet()
    {
        greeting.greet("Mark");
        assertTrue(greeting!=null);
    }
}

I also added the beans.xml file in the src/main/resources/META-INF folder

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

</beans>

When I run the test I get a NullPointerException at the marked line in the Tester class.

What do you think about the problem? I browsed a lot of documentation but it seem this problem is solved by adding the beans.xml , which is already in the classpath.

You can use CDI in jUnit test. Check this: http://jglue.org/cdi-unit/

YOu can use Arquillian to unit test CDI

http://arquillian.org/

Injection only works for managed beans (and a few other objects like servlets). Test classes get instantiated by JUnit and not by the CDI container, so injection does not work out of the box.

You need a special JUnit runner that injects dependencies into the instantiated test class - eg Pax Exam in CDI mode .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM