【问题标题】:Spring Boot multiple module test AutowiringSpring Boot 多模块测试自动装配
【发布时间】:2018-04-15 23:15:48
【问题描述】:

我有一个具有结构的多模块项目:

app/
  build.gradle
  settings.gradle
  app-web/
    src/main/java/example/
      Application.java
  app-repository/
    src/main/java/example/
      CustomerRepository.java
      Customer.java
    src/test/java/example/
      CustomerRepositoryTest

应用类:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

有仓库

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}

和存储库测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerRepositoryTest {

    @Autowired
    private CustomerRepository repository;

    @Test
    public void shouldSave() {
        // When
        final Customer saved = repository.save(new Customer());

        // Then
        assertThat(saved.getID()).isNotNull();
    }
}

现在当我运行这个测试时,我得到了错误:

找不到@SpringBootConfiguration,需要使用 @ContextConfiguration 或 @SpringBootTest(classes=...) 与您的测试

当我的存储库模块中有 Application 类但我需要将它们分开时,这不会出现。让它发挥作用的最佳方法是什么?

如果它有助于我的 Spring 依赖项是:

compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("com.h2database:h2")
testCompile("org.springframework.boot:spring-boot-starter-test")

使用插件org.springframework.boot:spring-boot-gradle-plugin:1.5.8.RELEASE

【问题讨论】:

  • 尝试将除Application(包括测试)之外的所有类移动到单独的包(例如src/main/java/example/subpackage)。我记得当@SpringBootApplication@SpringBootTest 在同一个包中时,组件扫描存在问题。我认为这是一个已知问题,但找不到参考
  • @jannis 我仍然遇到同样的错误 :( 有没有办法告诉测试如何在没有 Application 类的情况下配置它?
  • @jannis 我感觉@SpringBootTest 是为 REST 层设计的,所以可能与此有关
  • @SpringBootTest 换成@EnableAutoConfiguration 测试结果为绿色,但我不知道为什么

标签: java spring spring-boot spring-boot-test spring-boot-configuration


【解决方案1】:

似乎包层次结构问题。您必须将子项目 (app-web &amp; app-repository) 包含到 Gradle 的资源部分。我在我的 Maven 问题中遇到了同样的问题,并通过添加到资源部分来解决。 gradle不好,找了个链接:https://docs.gradle.org/current/userguide/java_plugin.html#sec:java_resources

【讨论】:

    猜你喜欢
    • 2016-03-29
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 2021-12-23
    • 2014-07-30
    相关资源
    最近更新 更多