Kohei Nozaki's blog 

Entries tagged [test]

Jukito integration with JPA and guice-persist


Posted on Sunday Jul 31, 2016 at 11:28AM in Technology


A DI container such as Guice helps you to assemble loosely-coupled classes that easy to write unit tests.

But integration tests, that are necessary thing as well as unit tests, it’s a different story from writing unit tests. writing integration tests involve many cumbersome initialization code of frameworks such as DI container, JPA provider or an application server. they tend to spread across testcases and make testcases messy.

If you use Guice as DI container, Jukito helps you to write integration tests. its official documentation covers some simple usecases, but not mentioned about integration with guice-persist. so in this entry I’ll introduce you how to integrate and begin writing clean testcases without messy boilarplate code with them.

Create an application to be tested

Consider we have a simple JPA entity and a service class which uses it.

An entity class named Employee:

@Entity
public class Employee implements Serializable {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    public Employee(final String name) {
        this.name = name;
    }
...

The service class to be tested named EmployeeService:

public class EmployeeService {

    @Inject
    private EntityManager em;

    @Transactional
    public Long save(final String name) {
        final Employee employee = new Employee(name);
        em.persist(employee);
        em.flush();
        return employee.getId();
    }

    public List<String> findAllNames() {
        return em.createQuery("SELECT e.name FROM Employee e ORDER BY e.name", String.class).getResultList();
    }
}

Create a module for testing

Next, we will create a module for testing (BTW I recommend you to use Module overriding for creating one for testing, based on production one). this would be something like:

// Taken from https://gist.github.com/JWGmeligMeyling/785e459c4cbaab606ed8 , thanks!
public class DatabaseModule extends AbstractModule {

    @Override
    protected void configure() {
        install(new JpaPersistModule("myPU"));
        bind(JPAInitializer.class).asEagerSingleton();
    }

    @Singleton
    private static class JPAInitializer {
        @Inject
        public JPAInitializer(final PersistService service) {
            service.start();
        }
    }
}

Create JpaJukitoRunner

Then, create a special TestRunner which extends JukitoRunner as follows:

public class JpaJukitoRunner extends JukitoRunner {

    public JpaJukitoRunner(final Class<?> klass) throws InitializationError, InvocationTargetException, InstantiationException, IllegalAccessException {
        super(klass);
    }

    public JpaJukitoRunner(final Class<?> klass, final Injector injector) throws InitializationError, InvocationTargetException, InstantiationException, IllegalAccessException {
        super(klass, injector);
    }

    private UnitOfWork unitOfWork;

    @Override
    protected Object createTest() throws Exception {
        this.unitOfWork = getInjector().getInstance(UnitOfWork.class);
        this.unitOfWork.begin();
        return super.createTest();
    }

    @Override
    public void run(final RunNotifier notifier) {
        notifier.addListener(new RunListener() {

            @Override
            public void testFinished(final Description description) throws Exception {
                // this ensures every tests use distinct entity manager instances
                unitOfWork.end();
            }
        });
        super.run(notifier);
    }
}

This ensures every tests use distinct EntityManager instances for each execution. without this, only one EntityManager instance will be used for all of executions of test cases because it is stored in a ThreadLocal and JUnit uses only one Thread by default for all test executions.

That means that many entities will be kept managed during an execution. consider if you have thousands of test classes in your project - entities will be shared across all of test execution. it will make your EntityManager fat, also your tests may get affected by 1st level cache which got dirty by other test executions.

Create a testcase

Finally, you can write a testcase as follows:

@RunWith(JpaJukitoRunner.class)
@UseModules(DatabaseModule.class)
public class EmployeeServiceTest {

    @Inject
    private EmployeeService sut;
    @Inject
    private EntityManager em;

    @Before
    @Transactional
    public void setUp() throws Exception {
        em.createQuery("DELETE FROM Employee").executeUpdate();
    }

    @Test
    public void saveShouldPersistJohnDoe() throws Exception {
        final String name = "John Doe";

        final long id = sut.save(name);

        final Employee employee = em.find(Employee.class, id);
        assertThat(employee.getName(), is(name));
    }

    @Test
    public void findAllNamesShouldReturnExpectedResult() throws Exception {
        sut.save("Jane Doe");
        sut.save("John Doe");

        final List<String> result = sut.findAllNames();

        assertThat(result.size(), is(2));
    }
}

You can see that there are no any cumbersome initialization code of JPA or database stuff. and note that you can use declarative transaction management by @Transactional, for both the sut class and populating test data into your database.

Cleaning 1st level cache

I have mentioned about bad effect of 1st level cache of EntityManager earlier in this entry, so you may consider that you want to clean 1st level cache. you can do it with em.clear(), or also something like following:

@RunWith(JpaJukitoRunner.class)
@UseModules(DatabaseModule.class)
public class EmployeeServiceTestManagesUOW {

    @Inject
    private Provider<EmployeeService> sut;
    @Inject
    private Provider<EntityManager> em;
    @Inject
    private UnitOfWork unitOfWork;

    @Before
    @Transactional
    public void setUp() throws Exception {
        em.get().createQuery("DELETE FROM Employee").executeUpdate();
    }

    @Test
    public void saveShouldPersistJohnDoe() throws Exception {
        final String name = "John Doe";
        newEntityManager();

        final long id = sut.get().save(name);

        newEntityManager();
        final Employee employee = em.get().find(Employee.class, id);
        assertThat(employee.getName(), is(name));
    }

    private void newEntityManager() {
        unitOfWork.end();
        unitOfWork.begin();
    }
}

In this test, there are three distinct EntityManagers involved in a test execution. the one in setUp(), another one in invocation of sut#save() and finally one for em#find() which is used for assertion.

But in my opinion, this is an overkill and using one shared EntityManager for one test execution would be sufficient. if it didn’t work well, something may wrong with your usage of JPA.

Conclusion

We have seen how testcases which involve JPA and guice-persist could be written cleanly with Jukito. it enables us to eliminate cumbersome boilarplate code for managing and invoking Injector, JPA initialization and manual transaction management. now our testcases look pretty clean.

Executable testcases and the example project can be obtained from my GitHub repository.

References


Excluding particular JUnit test cases that marked as slow in the time of execution


Posted on Sunday Nov 01, 2015 at 03:43PM in Technology


Sometimes we need to create some slow test cases that involve some external resources such as databases, or external API servers. They are necessary to ensure that your application can integrate with such external resources while vast majority of test cases should stick with fast-running plain unit testing.

In such case, We usually wants to exclude such slow test cases from the ones that are frequently executed in local development environment so that we can get timely response from the tests. In this posting, I introduce you a solution that avoids maintenance of any hand-made listing of test cases.

Creating a suite that scans and runs all of test cases exist in classpath

First, assume we have a simple production class named Hello.

public class Hello {
    public String greetings(String name) {
        return name != null ? "hello, " + name : "hi, what's your name?";
    }
}

We also have a couple of test cases against the preceding class:

public class HelloTest1 {
    @Test
    public void test() {
        System.out.println("Running " + getClass().getSimpleName());
        Assert.assertEquals("hello, kyle", new Hello().greetings("kyle"));
    }
}

public class HelloTest2 {
    @Test
    public void test() {
        System.out.println("Running " + getClass().getSimpleName());
        Assert.assertEquals("hi, what's your name?", new Hello().greetings(null));
    }
}

Next, We’d like to introduce a test suite that automatically includes the preceding two test cases. Put a following dependency to your pom.xml:

<dependency>
    <groupId>io.takari.junit</groupId>
    <artifactId>takari-cpsuite</artifactId>
    <version>1.2.7</version>
    <scope>test</scope>
</dependency>

And create a test suite that named AllTests as follows. You can run this suite from your IDE or executing mvn -Dtest=AllTests test.

@RunWith(ClasspathSuite.class)
public class AllTests {
}

Involving a slow test case and exclude it

First, Create a marker interface which indicates that this test is slow:

public interface SlowTest {
}

Next create a slow test case which annotated with @Category(SlowTest.class) that we would like to avoid execute it frequently:

@Category(SlowTest.class)
public class HelloSlowTest {
    @Test
    public void test() throws Exception {
        System.out.println("Running " + getClass().getSimpleName());
        Thread.sleep(3000);
    }
}

Finally create a test suite that automatically excludes the test cases annotated as slow but executes rest of the test cases:

@RunWith(Categories.class)
@ExcludeCategory(SlowTest.class)
@SuiteClasses(AllTests.class)
public class AllExceptSlowTests {
}

You can run it on a daily basis instead of selecting root of your entire project and execute tests from your IDE or Maven without any hand maintenance of the listings of tests. For example, mvn -Dtest=AllExceptSlowTests test produces following output in very short-term execution time:

...
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Picked up _JAVA_OPTIONS: -Dfile.encoding=UTF-8
Running category.suite.AllExceptSlowTests
Running HelloTest1
Running HelloTest2
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.084 sec
...

The complete resources can be obtained from https://github.com/lbtc-xxx/junit-category


How to bind / lookup DataSource via JNDI without container


Posted on Sunday Oct 25, 2015 at 10:58AM in Technology


While I prefer deploying JPA based apps to a Java EE container and test it via Arquillian as integration testing, some occasions won’t allow it and need arises that using a Servlet container or Java SE environment.

To supply information that required to connect the database (e.g. JDBC URL or credentials), it’s preferable to use JNDI rather than using DriverManager or javax.persistence.jdbc.* properties in persistence.xml because using JNDI eliminates the need of managing such information in the application codebase, also it enables to use the container managed connection pool which is more flexible and scalable over another.

In such case, hard-coded JNDI name of a DataSource may be a problem in the time of testing because JNDI lookup doesn’t work without container as is. So we may need some considering of involve pluggable mechanism of acquiring java.sql.Connection instance or creating persistence.xml for unit testing.

These solutions are not much difficult to implement, but it’s preferable if JNDI lookup does work without container as well because it will decrease amount of testing specific code. In this posting, I’ll give you a complete example of looking up a DataSource without container using bare InitialContext and the non-jta-datasource persistence descriptor definition.

Environment

  • tomcat-catalina artifact of Apache Tomcat 8.0.28: Enables binding a resource to JNDI context in Java SE environment

  • Apache Commons DBCP 1.4: Supplies BasicDataSource class so make the example in database independent manner

  • Apache Derby 10.12.1.1

  • EclipseLink 2.6.1

  • Oracle JDK8u60

Dependencies

<dependencies>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.derby</groupId>
        <artifactId>derby</artifactId>
        <version>10.12.1.1</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-catalina</artifactId>
        <version>8.0.28</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

persistence.xml

Note that the non-jta-data-source is used with JNDI name of DataSource.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="myPU" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <non-jta-data-source>java:comp/env/jdbc/database</non-jta-data-source>
        <class>entity.Employee</class>
        <shared-cache-mode>NONE</shared-cache-mode>
        <properties>
            <property name="javax.persistence.schema-generation.database.action" value="create"/>
            <property name="eclipselink.logging.level" value="FINE"/>
            <property name="eclipselink.logging.parameters" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

Employee.java

This is a simple JPA entity class that will be used in testing.

@Entity
public class Employee implements Serializable {
    @Id
    private Long id;
    private String firstName;
    private String lastName;

    // accessors omitted

Main.java

This binds a DataSource of Embedded in-memory Apache Derby database to java:comp/env/jdbc/database, then lookup it via InitialContext and EntityManagerFactory.

public class Main {
    private static final String JNDI = "java:comp/env/jdbc/database";

    public static void main(String[] args) throws Exception {
        bind();
        lookup();
        final EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPU");
        populate(emf);
        query(emf);
    }

    private static void bind() throws NamingException {
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

        final BasicDataSource ds = new BasicDataSource();
        ds.setUrl("jdbc:derby:memory:myDB;create=true");

        final Context context = new InitialContext();
        try {
            context.createSubcontext("java:");
            context.createSubcontext("java:comp");
            context.createSubcontext("java:comp/env");
            context.createSubcontext("java:comp/env/jdbc");
            context.bind(JNDI, ds);
        } finally {
            context.close();
        }
    }

    private static void lookup() throws NamingException, SQLException {
        final Context context = new InitialContext();
        try {
            final DataSource ds = (DataSource) context.lookup(JNDI);
            try (final Connection cn = ds.getConnection();
                 final Statement st = cn.createStatement();
                 final ResultSet rs = st.executeQuery("SELECT CURRENT_TIMESTAMP FROM SYSIBM.SYSDUMMY1")) {
                while (rs.next()) {
                    System.out.println(rs.getTimestamp(1));
                }
            }
        } finally {
            context.close();
        }
    }

    private static void populate(final EntityManagerFactory emf) {
        final EntityManager em = emf.createEntityManager();
        try {
            final EntityTransaction tx = em.getTransaction();
            tx.begin();
            final Employee emp = new Employee();
            emp.setId(1l);
            emp.setFirstName("Jane");
            emp.setLastName("Doe");
            em.persist(emp);
            tx.commit();
        } finally {
            em.close();
        }
    }

    private static void query(final EntityManagerFactory emf) {
        final EntityManager em = emf.createEntityManager();
        try {
            System.out.println(em.find(Employee.class, 1l));
        } finally {
            em.close();
        }
    }
}

Log

You can see the lookup() method dumped CURRENT_TIMESTAMP and EclipseLink successfully acquired a DataSource as follows.

2015-10-25 10:33:24.235
[EL Fine]: server: 2015-10-25 10:33:24.478--Thread(Thread[main,5,main])--Configured server platform: org.eclipse.persistence.platform.server.NoServerPlatform
[EL Config]: metadata: 2015-10-25 10:33:24.633--ServerSession(1323434987)--Thread(Thread[main,5,main])--The access type for the persistent class [class entity.Employee] is set to [FIELD].
[EL Config]: metadata: 2015-10-25 10:33:24.654--ServerSession(1323434987)--Thread(Thread[main,5,main])--The alias name for the entity class [class entity.Employee] is being defaulted to: Employee.
[EL Config]: metadata: 2015-10-25 10:33:24.656--ServerSession(1323434987)--Thread(Thread[main,5,main])--The table name for entity [class entity.Employee] is being defaulted to: EMPLOYEE.
[EL Config]: metadata: 2015-10-25 10:33:24.666--ServerSession(1323434987)--Thread(Thread[main,5,main])--The column name for element [firstName] is being defaulted to: FIRSTNAME.
[EL Config]: metadata: 2015-10-25 10:33:24.668--ServerSession(1323434987)--Thread(Thread[main,5,main])--The column name for element [lastName] is being defaulted to: LASTNAME.
[EL Config]: metadata: 2015-10-25 10:33:24.668--ServerSession(1323434987)--Thread(Thread[main,5,main])--The column name for element [id] is being defaulted to: ID.
[EL Info]: 2015-10-25 10:33:24.7--ServerSession(1323434987)--Thread(Thread[main,5,main])--EclipseLink, version: Eclipse Persistence Services - 2.6.1.v20150916-55dc7c3
[EL Fine]: connection: 2015-10-25 10:33:24.706--Thread(Thread[main,5,main])--Detected database platform: org.eclipse.persistence.platform.database.JavaDBPlatform
[EL Config]: connection: 2015-10-25 10:33:24.714--ServerSession(1323434987)--Connection(1872973138)--Thread(Thread[main,5,main])--connecting(DatabaseLogin(
	platform=>JavaDBPlatform
	user name=> ""
	connector=>JNDIConnector datasource name=>java:comp/env/jdbc/database
))
[EL Config]: connection: 2015-10-25 10:33:24.715--ServerSession(1323434987)--Connection(1465346452)--Thread(Thread[main,5,main])--Connected: jdbc:derby:memory:myDB
	User: APP
	Database: Apache Derby  Version: 10.12.1.1 - (1704137)
	Driver: Apache Derby Embedded JDBC Driver  Version: 10.12.1.1 - (1704137)
[EL Config]: connection: 2015-10-25 10:33:24.715--ServerSession(1323434987)--Connection(1634387050)--Thread(Thread[main,5,main])--connecting(DatabaseLogin(
	platform=>JavaDBPlatform
	user name=> ""
	connector=>JNDIConnector datasource name=>java:comp/env/jdbc/database
))
[EL Config]: connection: 2015-10-25 10:33:24.716--ServerSession(1323434987)--Connection(1740223770)--Thread(Thread[main,5,main])--Connected: jdbc:derby:memory:myDB
	User: APP
	Database: Apache Derby  Version: 10.12.1.1 - (1704137)
	Driver: Apache Derby Embedded JDBC Driver  Version: 10.12.1.1 - (1704137)
[EL Info]: connection: 2015-10-25 10:33:24.747--ServerSession(1323434987)--Thread(Thread[main,5,main])--/file:/Users/kyle/src/jndi-se/target/classes/_myPU login successful
[EL Fine]: sql: 2015-10-25 10:33:24.784--ServerSession(1323434987)--Connection(762809053)--Thread(Thread[main,5,main])--CREATE TABLE EMPLOYEE (ID BIGINT NOT NULL, FIRSTNAME VARCHAR(255), LASTNAME VARCHAR(255), PRIMARY KEY (ID))
[EL Fine]: sql: 2015-10-25 10:33:24.85--ClientSession(1027495011)--Connection(1688470144)--Thread(Thread[main,5,main])--INSERT INTO EMPLOYEE (ID, FIRSTNAME, LASTNAME) VALUES (?, ?, ?)
	bind => [1, Jane, Doe]
[EL Fine]: sql: 2015-10-25 10:33:24.877--ServerSession(1323434987)--Connection(640808588)--Thread(Thread[main,5,main])--SELECT ID, FIRSTNAME, LASTNAME FROM EMPLOYEE WHERE (ID = ?)
	bind => [1]
Employee{id=1, firstName='Jane', lastName='Doe'}

The complete source code can be obtained from my GitHub repository.


Lean example of integration test Maven project for WildFly


Posted on Monday Feb 23, 2015 at 11:20PM in Technology


I created similar example before, but it was redundant. I created more lean version so leave here with some notes. check my GitHub repository for details.

The project contains AppServer class, which extends ExternalResource so it can be used with @Rule annotation of JUnit as follows. note that mavenit is the name of WAR file to be tested.

public class HelloImplIT {

    @ClassRule
    public static AppServer appServer = new AppServer();
    private static Hello sut;

    @BeforeClass
    public static void beforeClass() {
        sut = appServer.lookup("mavenit", HelloImpl.class, Hello.class);
    }

    @Test
    public void test() {
        Assert.assertEquals("Hello world!", sut.hello());
    }
}

The project is easy to use with both of IDE and standalone. to run IT classes with IDE, you need to launch the application server, deploy the project as WAR package, then run a IT class from IDE. if you launched the server at not 8080 port, specify the port in app-server.port system property.

To run IT classes in standalone Maven, use following command. it automatically launches WildFly instance with port offset of 30000, deploy the WAR file, running IT classes, undeploy the WAR and stops WildFly. the command is intended to use from a Jenkins job.

mvn verify -Pintegration-test-with-wildfly \
 -Djava.home=/Library/Java/JavaVirtualMachines/jdk8/Contents/Home/jre \
 -Djboss-as.home=/Users/kyle/servers/wildfly-8.2.0.Final \
 -Dwildfly.port=39990 \
 -Dapp-server.port=38080 \
 -Dwildfly.jvmArgs="-Djboss.server.base.dir=/Users/kyle/servers/wildfly-8.2.0.Final/standalone-mavenit -Djboss.socket.binding.port-offset=30000 -ea"

You can configure following parameters through command line argument:

  • JAVA_HOME-Djava.home

  • WildFly distribution ⇒ -Djboss-as.home

  • jboss.server.base.dir ⇒ inside -Dwildfly.jvmArgs

  • Port offset ⇒ -Djboss.socket.binding.port-offset inside -Dwildfly.jvmArgs. you need to set -Dwildfly.port and -Dapp-server.port accordingly.


Switching EJB remote interface to local interface accordingly to environment


Posted on Monday Feb 23, 2015 at 01:33PM in Technology


Sometimes I need to create both of remote and local interface for EJBs. most of cases that were for integration testing. usually I used this way but that way still has some disadvantages as follows:

  • Annoying creation of both of interface (local and remote) is needed for all of each EJBs

  • Remote interface is redundant for most cases in production environment

To overcome these issues, I moved declarations of EJB from annotation to ejb-jar.xml. XML files are easy to be filtered with build tools such as Maven plugins. consider following case:

Business interface

public interface MyBean {
    String hello();
}

Implementation

public class MyBeanImpl implements MyBean {
    @Override
    public String hello() {
        return "Hello";
    }
}

Injection point

@WebServlet(name = "MyServlet", urlPatterns = "/")
public class MyServlet extends HttpServlet {
    @EJB
    MyBean myBean;
...
}

Test class

public class MyBeanIT {
    static Context ctx;
    static MyBean myBean;

    @BeforeClass
    public static void before() throws Exception {
        Properties props = new Properties();
        // ... put application server specific configuration here ...
        ctx = new InitialContext(props);
        myBean = (MyBean) ctx.lookup("ejb:/ejbxmltest//MyBeanImpl!org.nailedtothex.ejbxmltest.MyBean");
    }

    @AfterClass
    public static void after() throws Exception {
        ctx.close();
    }

    @Test
    public void test() throws Exception {
        org.junit.Assert.assertEquals("Hello", myBean.hello());
    }
}

ejb-jar.xml

<ejb-jar 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/ejb-jar_3_1.xsd"
         version="3.1">
    <enterprise-beans>
        <session>
            <ejb-name>MyBeanImpl</ejb-name>

            <!-- Will be replaced by business-local with replacer-plugin for production -->
            <business-remote>org.nailedtothex.ejbxmltest.MyBean</business-remote>

            <ejb-class>org.nailedtothex.ejbxmltest.MyBeanImpl</ejb-class>
            <session-type>Stateless</session-type>
        </session>
    </enterprise-beans>
</ejb-jar>

Remote interface and bean definition are presented in ejb-jar.xml instead of annotations. that definition will be used by IDE as default. EJBs will be deployed with a remote interface to the application server in development environment so we can test the bean through remote interface. a trick is in a profile named business-local in pom.xml which intended to use for production environment:

<profile>
	<id>business-local</id>
	<build>
		<!-- Following plugin definitions will be ignored by IDEA -->
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<configuration>
					<warSourceExcludes>WEB-INF/ejb-jar.xml</warSourceExcludes>
				</configuration>
			</plugin>
			<plugin>
				<groupId>com.google.code.maven-replacer-plugin</groupId>
				<artifactId>replacer</artifactId>
				<version>1.5.3</version>
				<executions>
					<execution>
						<phase>prepare-package</phase>
						<goals>
							<goal>replace</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<file>src/main/webapp/WEB-INF/ejb-jar.xml</file>
					<outputFile>target/${project.artifactId}/WEB-INF/ejb-jar.xml</outputFile>
					<token><![CDATA[(?<=</?)business-remote(?=>)]]></token>
					<value>business-local</value>
				</configuration>
			</plugin>
		</plugins>
	</build>
</profile>

maven-replacer-plugin replaces all of business-remote elements by business-local and put it into WEB-INF directory in the target directory, and tell maven-war-plugin to stop copying original WEB-INF/ejb-jar.xml so all of remote interfaces will be local interfaces in production environment. it is disabled by default and you have to enable it with invoke Maven with -P business-local argument. as to injection point (MyServlet) we don’t need to make any modification. @EJB or @Inject will work nevertheless whether the interface is local or remote.

Actually I really want to use Arquillian instead of remote EJB but unfortunately it doesn’t have some flexibility on my use case such as control of deployment timing at the present time.

The project used in test is available in my GitHub repository. the test was done with WildFly 8.2.0.Final.

CAUTION: invoking EJBs via local interface will call by reference but invoking via remote interface will call by value. you will get serious problems that different behavior between invoking local and remote interfaces. consider keep using remote interface on production (with accepting some performance degradation) or using modern testing framework such as Arquillian if necessary.