Search code examples
eventsjunitjava-ee-6mockito

Events in junit with Mockito


I try to test javax.enterprise.event.Event mocked by mockito but the following exception is thrown

Absent Code attribute in method that is not native or abstract in class file javax/enterprise/util/TypeLiteral

The class looks like

public class MyClassTest {
    @Mock Event<MyAlarm> event;
    //...
    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    //...
    }
    @Test
    public void myTest() {
        MyClass myClass = new MyClass();
        myClass.event = event;
        //...
        verify(event, never()).fire(any(MyAlarm.class));
        //...
    }
}

I add following to the pom.xml (maven project)

    <repository>
        <id>glassfish</id>
        <name>GlassFish Maven Repository</name>
        <url>http://maven.glassfish.org/content/groups/glassfish</url>
    </repository>

and include the glassfish-embedded-all in front of the javax (javaee-web-api) dependency

    <dependency>
        <groupId>org.glassfish.extras</groupId>
        <artifactId>glassfish-embedded-all</artifactId>
        <version>3.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>6.0</version>
        <type>jar</type>
        <scope>provided</scope>
    </dependency>

What I have done wrong or what do I misunderstand?


Solution

  • I made some slight mistakes. This article Unit Testing for Java EE by Adam Bien pointed me in the right direction. I removed the javaee-web-api dependency and add the glassfish-embedded-all dependency. My pom.xml looks like:

        <!-- .... -->
        <dependency>
            <groupId>org.glassfish.extras</groupId>
            <artifactId>glassfish-embedded-all</artifactId>
            <version>3.1.1</version>
            <scope>provided</scope>
        </dependency>
        <!-- <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>-->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>1.8.5</version>
            <scope>test</scope>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
        <!-- .... -->
      <repositories>
        <repository>
            <url>http://download.java.net/maven/2/</url>
            <id>java.net</id>
            <layout>default</layout>
            <name>java.net</name>
        </repository>
    </repositories>
    

    This works well for me and I can test java ee events (or mock-it out).