模拟 s3Service + junit 时出现 NullPointerException
NullPointerException while mocking s3Service + junit
我正在使用 amazon s3 进行文档存储。我需要为使用 s3.
的服务 class 编写测试用例
如何模拟 s3 对象?
我已经尝试了下面的方法,但是得到了 NPE。
示例测试用例:
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
@InjectMocks
private MyService myService;
@InjectMocks
private S3Service s3Service;
@Mock
private S3Configuration.S3Storage s3Storage;
@Mock
private AmazonS3 amazonS3;
@BeforeEach
public void setup() {
ReflectionTestUtils.setField(myService, "s3Service", s3Service);
ReflectionTestUtils.setField(s3Service, "s3Storage", s3Storage);
}
@Test
void getDetailTest() {
given(s3Storage.getClient()).willReturn(amazonS3);
given(s3Service.getBucket()).willReturn("BUCKET1");
given(s3Service.readFromS3(s3Service.getBucket(),"myfile1.txt")).willReturn("hello from s3 file"); //Null pointer exception
}
}
下面是 s3 服务 class 抛出 NPE 的示例。
public String readFromS3(String bucketName, String key) {
var s3object = s3Storage.getClient().getObject(new GetObjectRequest(bucketName, key));
//s3Object is getting null when run the test case.
//more logic
}
如何从 MyService
class 模拟 s3Service.readFromS3()
?
您不需要模拟测试中的每个对象,使用模拟来构建您的服务是非常好的...
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
private MyService myService;
@Mock
private AmazonS3 amazonS3;
@BeforeEach
public void setup() {
this.myService = new MyService(amazonS3);
}
@Test
void getDetailTest() {
given(this.amazonS3.getXXX()).willReturn(new Yyyyy());
assertEqual("ok", this.myService.doSmth());
}
}
我正在使用 amazon s3 进行文档存储。我需要为使用 s3.
的服务 class 编写测试用例如何模拟 s3 对象?
我已经尝试了下面的方法,但是得到了 NPE。
示例测试用例:
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
@InjectMocks
private MyService myService;
@InjectMocks
private S3Service s3Service;
@Mock
private S3Configuration.S3Storage s3Storage;
@Mock
private AmazonS3 amazonS3;
@BeforeEach
public void setup() {
ReflectionTestUtils.setField(myService, "s3Service", s3Service);
ReflectionTestUtils.setField(s3Service, "s3Storage", s3Storage);
}
@Test
void getDetailTest() {
given(s3Storage.getClient()).willReturn(amazonS3);
given(s3Service.getBucket()).willReturn("BUCKET1");
given(s3Service.readFromS3(s3Service.getBucket(),"myfile1.txt")).willReturn("hello from s3 file"); //Null pointer exception
}
}
下面是 s3 服务 class 抛出 NPE 的示例。
public String readFromS3(String bucketName, String key) {
var s3object = s3Storage.getClient().getObject(new GetObjectRequest(bucketName, key));
//s3Object is getting null when run the test case.
//more logic
}
如何从 MyService
class 模拟 s3Service.readFromS3()
?
您不需要模拟测试中的每个对象,使用模拟来构建您的服务是非常好的...
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
private MyService myService;
@Mock
private AmazonS3 amazonS3;
@BeforeEach
public void setup() {
this.myService = new MyService(amazonS3);
}
@Test
void getDetailTest() {
given(this.amazonS3.getXXX()).willReturn(new Yyyyy());
assertEqual("ok", this.myService.doSmth());
}
}