Friday, June 19, 2009

HowTo integrate JUnit and WebBeans

WebBeans provides an easy way to integrate it with JUnit.
I use for the examples WebBeans 1.0.0.PREVIEW1 and Junit4.

Follw these steps to integrate JUnit and WebBeans.

1. Create a base class called AbstractWebBeansContextTest
This super class contains the setup of the WebBeans Context and makes the WebBeans Manager available for its subclasses. You have to add the webbeans-se.jar to your build path. This jar provides the possibility to initialize the WebBeans context within a SE (Java StandardEdtion) environment.

import javax.inject.manager.Manager;
import org.jboss.webbeans.CurrentManager;
import org.jboss.webbeans.environment.se.StartMain;

public abstract class AbstractWebBeansContextTest {
public static final Manager manager;
static {
StartMain.main(new String[]{});
manager = CurrentManager.rootManager();
}
}

2. Put a beans.xml into the root-source directory of your testing project
In that beans.xml you could define your testing deployment types (e.g. @Mock, etc.). In our case this beans.xml left blank.

3. Create your test class
Create a new test class which is a subclass of AbstractWebBeansContextTest.
Annotate a method with @BeforeClass and initialize your WebBeans which you wan to use in your test case.
Annotate some other methods with @Test and use your initialized WebBeans.

public class MyTestCase extends AbstractWebBeansContextTest {

public static MyService service;

@BeforeClass
public static void startup() {
service = manager.getInstanceByType(MyService.class);
}

@Test
public void testServiceMethod() throws Exception {
...
service.myServiceMethod();
...
}
}

No comments:

Post a Comment