Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test this inputStream has been closed?

I have a Runnable along the lines of:

    public void run() {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            //more stuff here
        } 
        catch (Exception e) {
            //simplified for reading
        }
        finally {
            if(inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {}
            }
        }
    }

How do I test inputStream.close() was invoked? I am currently using Mockito and JUnit. I know injecting the inputStream in is an idea, but I don't want the resources to be used until run?() is called, hence it being a local variable. So how can I redesign my code in a way that allows me to test whether close was called?

like image 499
mogronalol Avatar asked Dec 10 '12 11:12

mogronalol


People also ask

How do you know if InputStream is closed?

There's no API for determining whether a stream has been closed. Applications should be (and generally are) designed so it isn't necessary to track the state of a stream explicitly. Streams should be opened and reliably closed in an ARM block, and inside the block, it should be safe to assume that the stream is open.

Does InputStream need to be closed?

You do need to close the input Stream, because the stream returned by the method you mention is actually FileInputStream or some other subclass of InputStream that holds a handle for a file. If you do not close this stream you have resource leakage.

How do I run a unit test in Junit?

To perform unit testing, we need to create test cases. The unit test case is a code which ensures that the program logic works as expected. The org. junit package contains many interfaces and classes for junit testing such as Assert, Test, Before, After etc.


1 Answers

If I understood the task correctly it could be like this

static boolean isClosed;

public void run() {
    InputStream inputStream = null;
    try {
        inputStream = new FileInputStream(file) {
            @Override
            public void close() throws IOException {
                isClosed = true;
                super.close();
            }
        };
        // more stuff here
like image 117
Evgeniy Dorofeev Avatar answered Oct 11 '22 20:10

Evgeniy Dorofeev