简体   繁体   中英

How to write a junit test for outputStream.write IO IOException

I have the following code

public static void writeToOutputStream(byte[] bytesArr, OutputStream outputStream) {
    try {
         outputStream.write(bytesArr);
        }
    catch (IOException e) {
           throw new NetModelStreamingException(
                "IOException occurd during writing to stream. Error 
                 Message:" + e.getMessage());
        }
}

I would like to write a JUnit to test my code will catch IOException if it happens.

PS: NetModelStreamingException is a custom Exception class that extends RuntimeException.

With JUnit4+ a method to test that exception handling is as expected could look like this (note that you need to fail the test if no exception is thrown).

    @Test
    public void testWriteToOutputStreamExceptionHandling() {
        //Dummy object for testing
        OutputStream exceptionThrowingOutputStream = new OutputStream() {
            public void write(byte[] b) throws IOException {
                throw new IOException(); //always throw exception
            }
            public void write(int b) {} //need to overwrite abstract method
        };

        try {
            YourClass.writeToOutputStream(new byte[0], exceptionThrowingOutputStream);
            fail("NetModelStreamingException expected");
        }
        catch (NetModelStreamingException e) {
            //ok
        }
    }

If you need that dummy object in other test methods as well, you should declare a member variable in your test case and initialise it in a setUp -method annotated with @Before . Also, you can hide the try-catch -block by declaring it in the @Test annotation.

This way, the code would look like this:

private OutputStream exceptionThrowingOutputStream;

@Before
public void setUp() throws Exception {
    exceptionThrowingOutputStream = new OutputStream() {
        @Override
        public void write(byte[] b) throws IOException {
            throw new IOException();
        }
        @Override
        public void write(int b) {}
    };
}

@Test(expected = NetModelStreamingException.class)
public void testWriteToOutputStreamExceptionHandling() throws NetModelStreamingException {
    YourClass.writeToOutputStream(new byte[0], exceptionThrowingOutputStream);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM