单元测试使用@SpringBootTest注解;默认扫描的项目定义的bean。有时需要引入第三方包bean来验证功能,实现方式如下:
1.添加测试类,使用@SpringBootTest注解
@SpringBootTest
@Import(com.common.util.UploadService.class)
class DemoApplicationTests {
@Autowired
private UploadService uploadService;
@Test
void contextLoads() {
try {
uploadService.init();
uploadService.uploadFileByUrl(testurl);
}catch (Exception exception){
System.out.println(exception.getMessage());
}
}
2.第二步,自定义类使用@Import指定需要扫描第三方包;
3.第三步,使用@Autowired注入第三方类,可能在调用方法前,需要调用第三方初始化方法。