【问题标题】:How to test spring beans in a sub-module project如何在子模块项目中测试spring bean
【发布时间】:2021-11-21 04:11:21
【问题描述】:

我的主要项目使用 spring-boot 和 maven。我创建了另一个 maven 模块,我想将它用作我的主项目的依赖项。所以我的新模块不需要是一个可运行的 spring-boot 项目。但我仍在使用一些 spring 注释,它也有自己的配置属性。

我遇到的问题是测试这个模块。我还没有把这个模块添加到主项目中,我想在我写完所有的测试和代码之后再做,因为它更方便。

所以我的问题是,是否可以在我的代码中没有真正的 Spring 应用程序上下文时编写测试?例如,下面的所有字段都为空,并且不可测试。是因为缺少应用程序上下文还是其他原因?

@ExtendWith(SpringExtension.class)
@EnableConfigurationProperties(value = CustomerConfiguration.class)
@TestPropertySource("classpath:application-test.properties")
public class CustomerServiceTest {

@Autowired
CustomerService service;   (NULL)

@Autowired
CustomerConfiguration config;  (NULL)


@Test
public void getCustomerTest() {
    ..some tests
    service.getCustomer();
}
}

和服务类:

 @Service
 public class CustomerService {
 }

我的 pom 是:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.vintage</groupId>
  <artifactId>junit-vintage-engine</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-engine</artifactId>
  <scope>test</scope>
</dependency>

【问题讨论】:

  • 自然没有应用程序上下文,因此无处可自动装配所有空值。您可以添加一个模块作为另一个应该解决问题的模块的依赖项。

标签: java spring spring-boot maven


【解决方案1】:

尝试将以下“主”类添加到您的测试源中:

@SpringBootApplication
@ConfigurationPropertiesScan
class TestApplication

fun main(args: Array<String>) {
    runApplication<TestApplication>(*args)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-19
    • 2016-10-03
    • 2011-11-19
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多