-1

Hello experts, I would like to start the Junit/mockito etc test framework as I have seen lots of blogs and even here itself people are suggesting to write test cases instead of sysout and all.. but I have been really struggling with testing :-(.. I went through tutorials and most of tutorial shows example of doing tests of sum sum, divide, addition etc.. ok I understood that but how I can use it in real life programming. Can some one please guide me and help writing the test case for example below VOID method:

public void callHtmls(List<String> pathList, Session session, Image img){
    Iterator<String> it = pathList.iterator();
    while(it.hasNext()){
        String path = it.next();
        String htmlPath = getHtmlPath(path); // call to a method
        if(htmlPath!=null){
            System.out.println("HTML Path is = " + htmlPath);
            try {
                callImagePrinter(htmlPath,session, img); //again call to a method
            }catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}

Please help me!!!!! I am having a nightmare because of the testing :-(

  • possible duplicate of [How to test void method with Junit testing tools?](http://stackoverflow.com/questions/1244541/how-to-test-void-method-with-junit-testing-tools) – kryger Mar 19 '15 at 21:54

1 Answers1

0

First find the dependencies:

  • input:
    • pathList, session, img
    • getHtmlPath()
  • output
    • callImagePrinter()
    • System.out

Then define what you want to test.

  1. The System-Output for a given pathList, session, img (probably easiest and best)
  2. That getHtmlPath is used if pathList is non-empty
  3. That callImagePrinter is called if pathList is non-empty
  4. That System.out is written to in the failure case

Example:

For stubbing the input with Mockito:

YourObject spy = spy(yourObject);
when(spy.getHtmlPath()).thenReturn("htmlpath");

then call your method:

callHtmls(asList("html1","html2"), null, null);

and verifying the output of callImagePrinter:

verify(spy).callImagePrinter(eq("htmlpath"), any(Session.class), any(Image.class));

Note that spy,when,eq and any are static methods of Mockito.

CoronA
  • 7,717
  • 2
  • 26
  • 53
  • Thanks Stefan for explanation. I am using the sysout only to check if i have correct path but want to remove it once i use the test cases. I understand the explanation but dont know how to implement it as a Junit/Mockito.. – java-tester Mar 20 '15 at 11:20
  • I appended an example with Mockito. – CoronA Mar 20 '15 at 16:29