One promise of @Alternative beans is to make it easier to mock out
things during testing.
In practice there are some problems to make that a reality.
For example, suppose we have this:
- foo-database-layer.jar
-- org/.../ProductionDatabaseSetup.class
--- Description: connects to the database on localhost (which is only
there on production).
-- org/.../TestDatabaseSetup.class
--- @Alternative
--- extends ProductionDatabaseSetup
--- Description: connects to an in-memory database and inserts testdata
in it.
- CustomerDAO
-- @Inject DatabaseSetup databaseSetup;
-- META-INF/beans.xml
--- Filled with other stuff
- foo-server.war
-- WEB-INF/lib/foo-database-layer.jar
-- WEB-INF/beans.xml
--- Filled with other stuff
Now, during the integrations tests of foo-server.war, we want to
replace ProductionDatabaseSetup with TestDatabaseSetup.
How?
1) Add a WEB-INF/beans-test.xml (just like logback-test.xml and logback.xml)
=> Does not work. It's ignored.
2) Change WEB-INF/beans.xml for the tests only.
Duplicate everything from the original.
Add declaration: <alternative>...TestDatabaseSetup</alternative>
=> Does not work. CustomerDAO still gets ProductionDatabaseSetup instead
of TestDatabaseSetup.
3) Change WEB-INF/lib/foo-database-layer.jar!META-INF/beans.xml for the
tests only.
Duplicate everything from the original.
Add declaration: <alternative>...TestDatabaseSetup</alternative>
=> Lots of code and tests are slow because of all the zipping and unzipping.
--
With kind regards,
Geoffrey De Smet