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;
}
Solved! Go to Solution.
Views
Replies
Total Likes
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
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
Thanks for ur reply .
hi @daniel-strmecki in my case this method is private and static is ther any other way to call
StreamToString()
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
Views
Likes
Replies
Views
Likes
Replies