mardi 9 juin 2020

Testing Synchronized method

I am trying to create a unit test to check if synchronized does the job on my method called pdfToBytes, how can i assert against my private method thats called inside the constructor

public class FaqAttachment {

private final String fileName = "FAQ.pdf";

public Attachment asAttachment() {
    return new Attachment(pdfToBytes(), fileName);
}

private synchronized byte[] pdfToBytes() {
    try (FileInputStream inputStream = new FileInputStream(new File(ClassLoader.getSystemResource(fileName).getFile()))) {
        return ByteStreams.toByteArray(inputStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Test

 @Test
public void shouldWorkWithMultipleThreadsAccessing() throws InterruptedException {
    ExecutorService service = Executors.newFixedThreadPool(2);
    FaqAttachment attachment = new FaqAttachment();

    for (int i = 0; i <= 100; i++) {
        service.submit(attachment::asAttachment);
    }
    service.awaitTermination(100, TimeUnit.MILLISECONDS);
    Assertions.assertEquals(100, attachment.asAttachment());
}

Aucun commentaire:

Enregistrer un commentaire