java如何在子模块项目中测试Springbean
我的主要项目使用SpringBoot和maven。我创建了另一个maven模块,我想将其用作主项目的依赖项。所以我的新模块不需要是一个可运行的spring引导项目。但我仍然在使用一些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>
# 1 楼答案
尝试将以下“主”类添加到测试源: