SpringBoot的单元测试时 ossClient注入报空指针异常的问题解决
在单元测试时使用@Autowired自动注入时注入失败时因为我们要注入的对象有可能是要整个项目启动之后才有的对象。
解决
所以在我们的测试类上使用@RunWith(SpringRunner.class)注解
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.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* @ClassName : ShopThirdPartyApplicationTests
* @Description : ShopThirdPartyApplicationTests
* @Author : XXXX
* @Date: 2022-08-11 17:59
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class ShopThirdPartyApplicationTests {
@Autowired
OSSClient ossClient;
@Test
public void test1() throws Exception {
// // Endpoint以杭州为例,其它Region请按实际情况填写。
// String endpoint = "XXXXXXXXXXXXXXXXx";
// // 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
// String accessKeyId = "XXXXXXXXXXXX";
// String accessKeySecret = "XXXXXXXXXXX";
//
// // 创建OSSClient实例。
// OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件流。
InputStream inputStream = new FileInputStream("D:\\MyProfile\\MySty\\6a1b2703a9ed8737.jpg");
System.out.println(ossClient == null);
ossClient.putObject("gulimall-xxa", "6a1b2703a9ed8737.jpg", inputStream);
// 关闭OSSClient。
ossClient.shutdown();
System.out.println("上传完成...");
}
}