Maven Web应用单元测试:beans.xml位置异常与修复方案咨询
I’ve dealt with this exact problem when using Deltaspike’s CdiControl for unit testing in Maven web applications—let’s break down why it happens and how to fix it.
The Root Cause
By default, Maven web apps store beans.xml in src/main/webapp/WEB-INF, which works perfectly for the deployed web application. But when running unit tests in a Java SE environment (not a full web container), the test runtime ignores the WEB-INF directory entirely. CDI requires beans.xml to be in the META-INF directory of the classpath for SE-mode initialization, so your CdiControl setup can’t find the file to bootstrap the container correctly.
Solution 1: Add a Test-Specific beans.xml
This is the simplest approach if you want to have a tailored configuration for tests:
- Create a
META-INFfolder undersrc/test/resources - Add a
beans.xmlfile here (you can reuse the content from your WEB-INF version, or simplify it if tests don’t need all production settings)
Here’s a minimal example:<?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_2_0.xsd" version="2.0" bean-discovery-mode="all"> </beans> - Now the test classpath will have a valid
beans.xmlin the correctMETA-INFlocation, so Deltaspike’s CdiControl can initialize the CDI container without issues.
Solution 2: Copy Production beans.xml to Test META-INF via Maven
If you want to avoid duplicating files, use the Maven Resources Plugin to automatically copy your existing beans.xml to the test classpath during build:
- Add this configuration to your
pom.xml:<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>3.3.1</version> <executions> <execution> <id>copy-beans-xml-to-test-meta-inf</id> <phase>process-test-resources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${project.build.testOutputDirectory}/META-INF</outputDirectory> <resources> <resource> <directory>${project.basedir}/src/main/webapp/WEB-INF</directory> <includes> <include>beans.xml</include> </includes> </resource> </resources> </configuration> </execution> </executions> </plugin> </plugins> </build> - This runs during the
process-test-resourcesphase, copying the productionbeans.xmlintotarget/test-classes/META-INF—making it available to your unit tests without manual file duplication.
内容的提问来源于stack exchange,提问作者fhossfel

