如何在子模块项目中测试spring bean



我的主要项目使用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();
}
}

And Service class:

@Service
public class CustomerService {
}

和我的诗是:

<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>

尝试添加以下"main"类到您的测试源:

@SpringBootApplication
@ConfigurationPropertiesScan
class TestApplication
fun main(args: Array<String>) {
runApplication<TestApplication>(*args)
}

最新更新