使用Maven-shade-plugin时无法在测试中加载ApplicationContext

问题描述

我有这个测试

@RunWith(springrunner.class)
@ContextConfiguration(locations = "classpath:some-context-test.xml")
@DirtiesContext
public class SomeClassIT {
  ...
  @Test
  public void someTestMethod() {
    ...
  }
  ...
}

从IntelliJ IDEA触发时运行没有问题,但由于错误而失败

[ERROR] someTestMethod(x.y.z.someClassIT)  Time elapsed: 0.001 s  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name
 'entityManagerFactory' defined in class path resource [meta-inf/db.xml]: Invocation of init method
 Failed; nested exception is org.hibernate.AssertionFailure: AttributeConverter class [class x.y.z.someConverter]
 registered multiple times
Caused by: org.hibernate.AssertionFailure: AttributeConverter class [class x.y.z.someConverter] registered
 multiple times

通过Maven执行时

mvn verify -DskipITs=false

但是,如果我从pom.xml中删除了maven-shade-plugin配置(项目正在使用它),那么即使通过maven,测试也会成功执行。

解决方法

在以下问答中找到了解决方案:https://stackoverflow.com/a/56589859/2806801。 maven-failsafe-plugin的参数classpathDependencyScopeExclude

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-failsafe-plugin</artifactId>
        <version>[...]</version>
        <configuration>
          <classpathDependencyScopeExclude>runtime</classpathDependencyScopeExclude>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

详细信息

由于使用了maven-shade-plugin,META-INF/db.xml(由some-context-test.xml导入)被加载了两次:

  1. jar:文件:/ C:/用户/.../ project / module1 / target / module1-v.1.0.0-SNAPSHOT.jar!/META-INF/db.xml
  2. jar:文件:/ C:/用户/.../.m2/存储库/.../project/module2/1.0.0/module2-1.0.0.jar!/META-INF/db.xml

将参数classpathDependencyScopeExclude设置为runtime之后,META-INF/db.xml仅从加载

  1. jar:文件:/ C:/用户/.../ project / module1 / target / module1-v.1.0.0-SNAPSHOT.jar!/META-INF/db.xml