Search code examples
javaunit-testingjunittestngjmockit

How do I verify that a specific constructor of a given class is called?


Suppose the following is the class under test:

public class MyClass {
    public void doSomething() throws FileNotFoundException {
        FileInputStream fis = new FileInputStream( "someFile.txt" );
        // .. do something about fis
    }
}

How do I verify that the constructor FileInputStream( String ) is called when the method doSomething() is invoked with a parameter "someFile.txt" using jMockit?

I'm not looking for an answer that is manual or not automated. I'm looking for an answer that employs automated unit-testing using tools such as JUnit or TestNG with the help of mocking and spying tools preferably jMockit.


Solution

  • Using the JMockit Expectations API, a test can verify constructor invocations just like method invocations. The test just needs to specify the class as @Mocked. For example:

    @Test
    public void exampleTestThatVerifiesConstructorCall(@Mocked FileInputStream anyFIS)
    {
        new MyClass().doSomething();
    
        new Verifications() {{ new FileInputStream("someFile.txt"); }};
    }
    

    That said, I would recommend to avoid mocking low-level classes like FileInputStream, which usually are just internal implementation details of the class under test. A better test would use an actual file and check somehow that it was read as expected.