Writing Junits Test for a method [closed]

I am new to Java. I want to write junits for this method, What parts are to be tested to gain full coverage?

public class S3Client {

    private final AmazonS3 s3Client;

    @Inject @Named(S3_KIOSK_EVENT_BUCKET)
    private final String bucketName;
    public boolean save(String folderName, String filename, String messageBody) {

        try {
            s3Client.putObject(bucketName, String.format("%s/%s.json",folderName,filename), messageBody);
            log.debug("Message Published in S3 Bucket");
            return true;

        } catch (AmazonServiceException e) {
            log.error("File cannot be added. Error: "+ e);
        }
        return false;
    }
}

Answer

it depends on the type of test, if it is unitary you could mock the amazon client and simulate a positive response after the put object method call or a negative response which ever you want, if it is integration it should have a test method that receives the same parameters as the save method and vary the combination to be successful and also fail, keep in mind that the coverage is based on the sectors of the code where the test passes that includes the try catch

S3Client subject;

AmazonS3 s3Client;

@BeforeAll
static void setup(){
    s3Client = mockito.mock(AmazonS3.class);
    subject = new S3Client(s3Client);
}

@Test
public void saveObjectInS3Test(){

    //We simulate that everithing is ok 
    when(s3Client.putObject(mockito.isAny(),mockito.isAny(),mockito.isAny())).thenReturns(new PutObjectResult())
    assertEqual(subject.save("fooForlderName","fooFileName","fooMessageBody"),true);

    //Then we can simulate an exception
    when(s3Client.putObject(mockito.isAny(),mockito.isAny(),mockito.isAny())).thenThrow(AmazonServiceException.class);
    assertEqual(subject.save("fooForlderName","fooFileName","fooMessageBody"),false);

}

Leave a Reply

Your email address will not be published. Required fields are marked *