0

我正在使用 Spring 的 @Configurable 在 Dropwizard 应用程序中自动装配使用“new”构造的 bean。我有一个集成测试,它使用 DropwizardAppRule 来启动应用程序,并使用 aspectj-maven-plugin 进行编译时编织。

当我从 IDEA 构建并运行集成测试时,bean 已按预期连接并且测试通过。

当我运行“mvn clean install”时,bean 没有连接,测试失败并出现 NullPointerException。

当我运行“mvn clean install -DskipTests”并启动应用程序时,bean 连接正确。

我的问题是为什么在“mvn clean install”期间它会失败?

aspectj-maven-plugin 在流程源阶段运行,因此应该在集成测试运行之前检测类:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <version>1.8</version>
    <configuration>
      <complianceLevel>1.8</complianceLevel>
      <source>1.8</source>
      <target>1.8</target>
      <aspectLibraries>
        <aspectLibrary>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aspects</artifactId>
        </aspectLibrary>
      </aspectLibraries>
    </configuration>
    <executions>
      <execution>
        <phase>process-sources</phase>
        <goals>
          <goal>compile</goal>
          <goal>test-compile</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

如果我反编译这个类,我可以看到它确实已经被检测过了。

如果我在 @Autowired 设置器中设置断点并从 IDEA 运行集成测试,我可以看到该类正在由 Spring 连接。

运行“mvn clean install”时,它根本不会在设置器中中断。

用 @Resource 替换 @Autowired 没有帮助。

我有一个具有 @EnableSpringConfigured 的 Spring 配置类。我最好的猜测是 DropwizardAppRule 没有使用正确的 Spring 配置,尽管其他 spring 组件正在正确管理。

任何帮助是极大的赞赏。谢谢你。

编辑

我还测试了默认的surefire(maven 3.2.5)和:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
</plugin>
4

1 回答 1

0

我想通了,但需要更多的上下文来解释这个问题。@Configurable 在枚举中被实例化,如下所示:

public enum Day {
    MONDAY(new MyConfigurableObject()),
    ...
}

单元测试和集成测试一起运行,单元测试在 spring 上下文可用之前实例化枚举。因为枚举存在于静态上下文中,所以集成测试随后使用了未连接的枚举。

解决方案是将单元测试和集成测试执行分开。我使用 maven-failsafe-plugin 做到了这一点,如下所示:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <configuration>
        <excludes>
            <exclude>it/**</exclude>
        </excludes>
    </configuration>
</plugin>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.18.1</version>
    <configuration>
        <includes>
            <include>it/**</include>
        </includes>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
</plugin>
于 2015-09-22T07:25:50.730 回答