Issue
I am using amazon s3 for the document storage. I need to write test cases for the service class which is using s3.
How to mock the s3 object ?
I have tried the below, but getting the 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
}
}
Below is the s3 service class sample where it is throwing 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
}
How to mock s3Service.readFromS3()
from MyService
class ?
Solution
You don't need to mock each object in your test, it's quite fine to construct your service using mocks ...
@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());
}
}
Answered By - lazylead
Answer Checked By - Marie Seifert (JavaFixing Admin)