1

I've two functions addKeywords and search which have void return type and search function prints results to the console. Here is the code

 void addKeywords(String video)throws IOException{


    InputStreamReader ip = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(ip);

    Integer previousVal=0;

    if(!videoKeyword.containsKey(video) && videoNames.contains(video)){
        videoKeyword.put(video,new HashSet<String>());
    }
    else if(!videoNames.contains(video)){
        System.out.println("Video is not a part of lookup");
    }

    System.out.println("Enter keywords for video");
    String keyword =br.readLine();

    if(!keywordLength.containsKey(video))
        keywordLength.put(video, 0);

    if((keywordLength.get(video)+keyword.length())<500){
        videoKeyword.get(video).add(keyword);
        previousVal=keywordLength.get(video);
        keywordLength.put(video, previousVal+keyword.length());
    }
    else{
        System.out.println("Maximum length exceeded for video "+ video);
    }
    if(!kewordVideo.containsKey(keyword)){
        kewordVideo.put(keyword,new HashSet<String>());
    }
    kewordVideo.get(keyword).add(video);
 }

 void search(String searchKey){
    for (Entry<String, HashSet<String>> entry : videoKeyword.entrySet()) {
        for (String s : entry.getValue()) {
            if (s.startsWith(searchKey)) {
                System.out.println(searchKey+" is mapped to "+entry.getKey());
                break;
            }
        }
     }
 }

I have written junit tests

 public class MyUnitTest extends CultureMachineAssignment {
      CultureMachineAssignment testObj =new CultureMachineAssignment();
      testObj.insertDataIntoSet();
      testObj.addkeywords("video1");

     @Test
     public void testVideo() {
        assertEquals("video1", testObj.search("abcd"));
    }
}

I am getting following errors

The method assertEquals(Object, Object) in the type Assert is not applicable for the arguments (String, void)

  • Syntax error on token ""video1"", delete this token
  • Syntax error on token(s), misplaced construct(s)

I am not sure if this is the correct way to write junit test cases for functions with void return type and which prints output to console. Can someone please tell me correct code ?

Pravin Kottawar
  • 71
  • 2
  • 18
  • 2
    Why don't you simply let the `search(...)` method return a String ? – romfret May 27 '15 at 07:33
  • Issue with allowing search method return is there may be multiple outputs so once i return remaining will not be printed so I am not using return – Pravin Kottawar May 27 '15 at 07:45
  • 1
    You can also return a `List` or a `String[]` and then write a function to print it. – romfret May 27 '15 at 07:48
  • fine i did it but still I am having syntax errors which i am not able to resolve – Pravin Kottawar May 27 '15 at 08:53
  • What is your syntax errors ? – romfret May 27 '15 at 08:59
  • Syntax error on token "insertDataIntoSet", Identifier expected after this token in MyUnitTest for ` testObj.insertDataIntoSet(); testObj.addkeywords("video1");` – Pravin Kottawar May 27 '15 at 09:00
  • It seems you are calling methods of the `testObj`directly in the class and not in a method. Only fields can be here. Encapsulate your initialisation with a `init()` method along with the annotation `@Before`. – romfret May 27 '15 at 09:15
  • I did that with `@Before public void init() throws IOException{ testObj1.insertDataIntoSet(); testObj1.addKeywords("video1"); }` now after running I am getting java.lang.stackoverflow error – Pravin Kottawar May 27 '15 at 09:23
  • It depends of what you want... `@Before`execute the method each time before a test method. `@BeforeClass`excutes the method one time a the initilialization. Or you can just cut/paste your two lines of code in your `testVideo` method. In a general way, you have to handle your lists (clear it if needed) – romfret May 27 '15 at 09:30
  • I tried all 3 options still I am getting java.lang.Stack()Overflow error .`java.lang.StackOverflowError at cultureMachine.CultureMachineAssignment.(CultureMachineAssignment.java:13) at cultureMachine.CultureMachineTestCases.(CultureMachineTestCases.java:11) at cultureMachine.CultureMachineTestCases.(CultureMachineTestCases.java:14) ` – Pravin Kottawar May 27 '15 at 09:34
  • `extends CultureMachineAssignment` don't have to be here, I think. It is complicated to help you more, we don't have all the code for testing. – romfret May 27 '15 at 09:38

2 Answers2

2

You can redirect the System.out or System.err messages with System.setOut(printStream) and System.setErr(printStream) functions.
That way you will be able to get the System.out messages into a printstream object and can read it.

Codebender
  • 14,221
  • 7
  • 48
  • 85
1

You need to pass System.out to the constructor of the class in the form of PrintStream and then write to it later. So you can replace it in a unit test with a custom stream into a String and verify it:

final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(byteArrayOutputStream);

ps.println("...");

assertEquals("expectedOutput", byteArrayOutputStream.toString())

(You should also pass System.in as a parameter to further decouple)


Update

As @kryger pointed out: You should return the result as a String and move printing responsibility to the caller.

thomas.mc.work
  • 6,404
  • 2
  • 26
  • 41
  • 3
    If we were to recommend a code change to help OP fix the testing problem, I'd argue that passing a mutable, writable `Stream` is a much worse solution than making the method more functional by making it return the results and move printing responsibility to the caller (as per *romfet*'s comment) – kryger May 27 '15 at 09:01
  • @kryger Yes, I agree. – thomas.mc.work May 27 '15 at 09:19
  • "romfret" with an "r" ;). We are all agree so. – romfret May 27 '15 at 09:25
  • Obviously, "@romfret with an **r**" (or even *two* "r"s :)). Sadly autocomplete doesn't work for people who didn't comment under the same question. – kryger May 27 '15 at 09:55
  • @kryger Oh yes I see... no prob anyway ! :) – romfret May 27 '15 at 09:58