DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Use a CDI Alternative as a Mock Implementation for a Stateless Session Bean

Use a CDI Alternative as a Mock Implementation for a Stateless Session Bean

See how you can use the @Alternative annotation to mock up the implementation of a stateless session bean.

Anghel Leonard user avatar by
Anghel Leonard
CORE ·
Oct. 21, 16 · Tutorial
Like (6)
Save
Tweet
Share
14.48K Views

Join the DZone community and get the full member experience.

Join For Free

A great feature of CDI (supported by Java EE starting with version 6) consist in alternatives. Basically, we want to specify an alternative for an injected object. Let's have a simple scenario commonly followed in JSF applications that uses stateless session beans to interact with a database. Supposing that we write the business logic part to query the database. We can start with an interface as:

public interface IFooService {
    List getAllFoo();
}


Furthermore, we can write a stateless session bean that implements this interface and make use of JPA's capabilities to query the database. Well, things didn't get too far for this part because the database is not ready and all we can provide is a skeleton like below:

@Stateless
public class FooService implements IFooService {
   
    @PersistenceContext(unitName = "fooPU")
    private EntityManager em;
    @Override
    public List getAllFoo() {
        // perform the query
        ...
        return new ArrayList();
    }
}


Finally, we inject the stateless session bean in a CDI managed bean as below:

Named
@RequestScoped
public class FooBean {
    private static final Logger LOG = Logger.getLogger(FooBean.class.getName());
    @Inject
    private IFooService fooService;
    public void loadAllFoo() {
        List allfoo = fooService.getAllFoo();
        LOG.log(Level.INFO, "allfoo:{0}", allfoo);
    }
}


Now, let's suppose that we want to run/test this method, but we have an issue. The data that we expect from the database will not be available, so we think to mock this service and provide a set of dummy data as below:

@Stateless
public class FooServiceMock implements IFooService {
    @Override
    public List getAllFoo() {
        return Arrays.asList("foo 1", "foo 2", "foo 3");
    }
}


But, if we test the code now, we will obtain an error of type ambiguous dependencies. In order to fix this error, we simply annotated our mock with @Alternative annotation:
@Alternative
@Stateless
public class FooServiceMock implements IFooService {
    @Override
    public List getAllFoo() {
        return Arrays.asList("foo 1", "foo 2", "foo 3");
    }
}


If we run now, there will be no errors, but the application will not use the mock. This is happening because our alternative is not activated. We must accomplish this in the beans.xml, as below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       bean-discovery-mode="all">
   
    <alternatives>
        <class>beans.FooServiceMock</class>
    </alternatives>
</beans>


Done! Now the FooBean will use the FooServiceMock instead of FooService. When the database will be ready/queryable we will simply deactivate the alternative.

Via CDI-Unit we can write a quick test that also uses our mock:

@RunWith(CdiRunner.class)
@ActivatedAlternatives(FooServiceMock.class)
public class FooBeanTest {
   
    @Inject
    FooBean fooBean;
    @Test
    @InRequestScope
    public void testStart() {
        fooBean.loadAllFoo();
    }   


The complete example is available here.
CDI Bean (software) Spring Framework Session (web analytics) Database Implementation

Published at DZone with permission of Anghel Leonard, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Beginners’ Guide to Run a Linux Server Securely
  • Implementing Infinite Scroll in jOOQ
  • Getting Started With JMS-ActiveMQ: Explained in a Simple Way
  • 2023 Software Testing Trends: A Look Ahead at the Industry's Future

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: