Skip to content

New tests for COSName.writePDF#164

Closed
Deee92 wants to merge 1 commit intoapache:trunkfrom
Deee92:tests-with-mocks
Closed

New tests for COSName.writePDF#164
Deee92 wants to merge 1 commit intoapache:trunkfrom
Deee92:tests-with-mocks

Conversation

@Deee92
Copy link

@Deee92 Deee92 commented Jun 29, 2023

Hello!

I tried a few command-line tools on some PDF documents, and found that org.apache.pdfbox.cos.COSName.writePDF(OutputStream) was invoked during the execution.

Here are two tests that verify the invocation of java.io.OutputStream.write(int) within writePDF. The OutputStream object is mocked within the tests.

The following test verifies the parameters with which write should be invoked within writePDF:

@Test
public void testBytesWrittenToOutputStreamForCOSNameType() throws IOException
{
    // Arrange
    COSName cosNameType = COSName.TYPE;
    OutputStream mockOutputStream = Mockito.mock(OutputStream.class);

    // Act
    cosNameType.writePDF(mockOutputStream);

    // Assert
    verify(mockOutputStream, atLeastOnce()).write(47);
    verify(mockOutputStream, atLeastOnce()).write(84);
    verify(mockOutputStream, atLeastOnce()).write(121);
    verify(mockOutputStream, atLeastOnce()).write(112);
    verify(mockOutputStream, atLeastOnce()).write(101);
}

The following test verifies that write should be called exactly five times within writePDF:

@Test
public void testNumberOfBytesWrittenToOutputStreamForCOSNameType() throws IOException
{
    // Arrange
    COSName cosNameType = COSName.TYPE;
    OutputStream mockOutputStream = Mockito.mock(OutputStream.class);

    // Act
    cosNameType.writePDF(mockOutputStream);

    // Assert
    verify(mockOutputStream, times(5)).write(anyInt());
}

What do you think?

Thanks!

@THausherr
Copy link
Contributor

I don't see how this improves test coverage; at most, this shows an interesting example on how to use mockito.

@Deee92
Copy link
Author

Deee92 commented Jul 1, 2023

Hi @THausherr, that's a fair point!
However, the integer parameters (47, 84, 112, 121, 101) with which OutputStream.write(int) is called within COSName.writePDF(OutputStream), as well as the number of times it should be called (5) correspond to actual behavior during execution.
Additionally, I did some mutation analysis, and found that the two tests can kill mutants introduced within writePDF.
These make them potentially useful as regression tests. 🚀

@lehmi
Copy link
Contributor

lehmi commented Jul 8, 2023

Your is a valid test, but it won't increase out test coverage as that method in question is covered by other tests already.

@Deee92 Deee92 closed this by deleting the head repository Feb 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants