Skip to content

Mocking java.io.FileInputStream leads to hanging tests #2025

@Damtev

Description

@Damtev

Description

Some tests generated for a MUT use the class java.io.FileInputStream with mocking it (using `mock always, for example) hang. Consider the following MUT:

public int read(String s) throws IOException {
        java.io.FileInputStream fis = new java.io.FileInputStream(s);
        byte[] b = new byte[1000];
        return fis.read(b);
}

If java.io.FileInputStream is added to the list of mock always classes (in the IntellliJ IDEA plugin or using CLI), the following test will be generated by symbolic execution:

public void testRead_FileInputStreamRead() throws IOException {
        org.mockito.MockedConstruction mockedConstruction = null;
        try {
            mockedConstruction = mockConstruction(java.io.FileInputStream.class, (java.io.FileInputStream fileInputStreamMock, org.mockito.MockedConstruction.Context context) -> {/*(when(fileInputStreamMock.read(any()))).thenReturn(0)*/});
            DataNode dataNode = new DataNode(null);

            int actual = dataNode.read(null);

            assertEquals(0, actual);
        } finally {
            mockedConstruction.close();
        }
    }

It hangs at the line DataNode dataNode = new DataNode(null);.

To Reproduce

Steps to reproduce the behavior:

  1. Add the java.io.FileInputStream class to the list mock always (in plugin or CLI).
  2. Generate tests for the method above
  3. Run generated tests.

Expected behavior

All tests pass.

Actual behavior

At least one of the tests hangs.

Environment

No special environment.

Additional context

It seems like it happens because the class java.io.FileInputStream is used in the class loader during loading CUT, but this class is already mocked. There are two possible solutions:

  1. Sort models from the symbolic execution - firstly models that do not require mocks, then models that use mocks in the order of topological sort based on dependencies and generate corresponding variables at the code generation part in this order.
  2. Load all used classes (without initialization) before running all tests.

Metadata

Metadata

Assignees

Labels

comp-codegenIssue is related to code generatorctg-bugIssue is a bug

Type

No type

Projects

Status

Todo

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions