原代码
package com.atguigu.gulimall.product;import com.aliyun.oss.OSSClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;//开始我是没有@RunWith(SpringRunner.class)注解的
//@RunWith(SpringRunner.class)
@SpringBootTest
public class GulimallProductApplicationTests {@ResourceOSSClient ossClient;@Value("${spring.cloud.alicloud.oss.endpoint}")String a;@Testpublic void testUpload() throws FileNotFoundException {System.out.println(a);String filePath= "E:\\huawei.png";InputStream inputStream = new FileInputStream(filePath);ossClient.putObject("gulimall-xx","huawei.png",inputStream);ossClient.shutdown();System.out.println("上传完成。。。。");}
}
结果我单元测试的时候报空指针,spring并没有注入我这个OSSClient 这个bean,经查,是因为SpringBoot的版本不一样导致的这个问题,一开始创建的是高版本的SpringBoot项目,后面在代码中把依赖版本降低了,但创建项目默认生成的代码还是高版本的
版本问题
针对SpringBoot的测试类,2.2版本之前和之后是不一样的。 在2.2版本之前需要添加注解 @SpringBootTest 和 @RunWith(SpringRunner.class) ,在Spring容器环境下进行测试,因为 @Test 导包的是org.junit.Test。 在2.2版本之后只需要添加注解 @SpringBootTest,其中@Test导包为org.junit.jupiter.api.Test。
包路径不一致
注意测试类的包名和启动类的包名一定要一致,否则扫描不到bean对象会报空异常,如下图:
总结:在使用@SpringBootTest时,最好指定启动类,如:
@SpringBootTest(classes = {xxx.class})