how to write junit for the below code | Community
Skip to main content
djohn98390536
Level 4
November 3, 2024
Solved

how to write junit for the below code

  • November 3, 2024
  • 1 reply
  • 1068 views

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;

}

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by daniel-strmecki

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!"); }

 


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

1 reply

daniel-strmecki
Community Advisor and Adobe Champion
Community Advisor and Adobe Champion
November 3, 2024

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

djohn98390536
Level 4
November 4, 2024

Hi @daniel-strmecki 

Thanks for ur reply .