我正在使用amazons3进行文档存储。我需要为使用s3的服务类编写测试用例。
如何模拟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
}
}
下面是抛出NPE的s3服务类示例。
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
类模拟s3Service.readFromS3()
?
1条答案
按热度按时间twh00eeo1#
您不需要在测试中模拟每个对象,使用模拟来构造服务是很好的...