Expand my Community achievements bar.

SOLVED

how to write junit for the below code

Avatar

Level 4

private static String StreamToString(InputStream is) {

String outString= null;

try {

StringWriter writer = new StringWriter();

IOUtils.copy(is, writer, "UTF-8");

theString = writer.toString();

} catch (Exception e) {

theString = StringUtils.EMPTY;

}

return outString;

}

1 Accepted Solution

Avatar

Correct answer by
Level 8

Hi @djohn98390536,

in case your method is private, then you shouldn't write a unit test for it at all. This is considered bad practice by most. Instead, focus on testing your public methods that will cover the logic in your private methods as well.

 

Good luck,

Daniel

View solution in original post

5 Replies

Avatar

Level 8

Hi @djohn98390536,

to write a Junit test for the code sample I think first you need to fix the code as your variable outString is initialized but not assigned to any value:

 

private static String StreamToString(InputStream is) {
    String outString = null;
    try {
        StringWriter writer = new StringWriter();
        IOUtils.copy(is, writer, "UTF-8");
        outString = writer.toString(); 
    } catch (Exception e) {
        log.warning("Exception writting string", e);
        outString = StringUtils.EMPTY; 
    }
    return outString;
}

 

 Then you should be able to write a Unit test like:

 

@Test
public void testStreamToString_withNormalInput() {
    String input = "Hello, world!";
    InputStream is = new ByteArrayInputStream(input.getBytes());
    String result = YourClassName.StreamToString(is);
    assertEquals(input, result);
}

 

 

Good luck,

Daniel

Avatar

Level 4

hi @daniel-strmecki in my case this method is private and static is ther any other way to call 

StreamToString()

 

Avatar

Level 2

Hi @djohn98390536 

For private static method you can use Reflection API like this - 

 

 @Test
    void checkMethod() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String input = "Hello, world!";
        InputStream is = new ByteArrayInputStream(input.getBytes());
        TestUtil testUtil = new TestUtil();
        Method privateMethod = TestUtil.class.getDeclaredMethod("StreamToString",InputStream.class);
        privateMethod.setAccessible(true);
        // invoke the private method for test
        Object s = privateMethod.invoke(testUtil, is);
        assertEquals(s.toString(),"Hello, world!");

    }

 

Avatar

Correct answer by
Level 8

Hi @djohn98390536,

in case your method is private, then you shouldn't write a unit test for it at all. This is considered bad practice by most. Instead, focus on testing your public methods that will cover the logic in your private methods as well.

 

Good luck,

Daniel