Domanda

Introduction: Consider following simplified unit test:

@Test
public void testClosingStreamFunc() throws Exception {
    boolean closeCalled = false;
    InputStream stream = new InputStream() {
        @Override
        public int read() throws IOException {
            return -1;
        }

        @Override
        public void close() throws IOException {
            closeCalled = true;
            super.close();
        }
    };
    MyClassUnderTest.closingStreamFunc(stream);
    assertTrue(closeCalled);
}

Obviously it does not work, complains about closed not being final.

Question: What is the best or most idiomatic way to verify that the function under test does call some method, like close() here, in context of Java unit tests?

È stato utile?

Soluzione

What about using regular class with instance variable:

class MyInputStream {
    boolean closeCalled = false;

    @Override
    public int read() throws IOException {
        return -1;
    }

    @Override
    public void close() throws IOException {
        closeCalled = true;
        super.close();
    }

    boolean getCloseCalled() {
        return closeCalled;
    }
};
MyInputStream stream = new MyInputStream();

If you don't want to create your own class consider using any mocking framework, e.g. with Jmokit:

@Test
public void shouldCallClose(final InputStream inputStream) throws Exception {
    new Expectations(){{
        inputStream.close();
    }};

    MyClassUnderTest.closingStreamFunc(inputStream);
}

Altri suggerimenti

I think you should have a look at mockito which is a framework to do this kind of test.

For example you can check the number of invocation: http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#4

import java.io.IOException;
import java.io.InputStream;

import org.junit.Test;

import static org.mockito.Mockito.*;

public class TestInputStream {

    @Test
    public void testClosingStreamFunc() throws Exception {
        InputStream stream = mock(InputStream.class);
        MyClassUnderTest.closingStreamFunc(stream);
        verify(stream).close();
    }

    private static class MyClassUnderTest {
        public static void closingStreamFunc(InputStream stream) throws IOException {
            stream.close();
        }

    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top