原代碼
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})