user3331579
user3331579

Reputation: 33

Java unit test for void methods

First of all I would like to apologise about my language skill, but my mother language isn't english.

I have got a little source code, which is:

public void hello(List l){    
    switch (l.get(0) {    
    case "hello":    
         System.out.println("Hello!");    
    case "world":    
        System.out.println("World");    
        break;    
    }    
}

And I have to write a unit test, which can testing about this code. But my skill is not enough about it. Could somebody help me please? Some example or book or something. I don't know how can I starting it!

I am appreciate.

Thanks

Upvotes: 3

Views: 1784

Answers (5)

Bohemian
Bohemian

Reputation: 425033

You could test the method by launching a new JVM and calling code that calls this then capturing the output, but...

Simpler to refactor the code so you can test it: Extract a method that returns a String, leaving a wrapper method that prints the result, but you test the extracted method.

Upvotes: 2

Toon Borgers
Toon Borgers

Reputation: 3658

You can change the outputstream to a mock one like this (using Mockito).

PrintStream mockStream = Mockito.mock(PrintStream.class);
PrintStream original = System.out;
System.out = mockStream;

//call your method here:
hello(myList);

//check if your method has done its job correctly
Mockito.verify(mockStream).println("Hello!");
//clean up
System.out = orig;

Also, don't forget to put a break after your first case or it will fall through and print the second time as well.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691715

To be able to test this method, you'd have to be able to tell what has been printed to System.out. You would thus have to replace System.out by another stream, writing in memory, so that you can inspect the content of the stream after the method has been called. This is doable, but not so easy.

You would make your method more reusable, and more testable, if instead of printing to System.out, it returned a String instead. You couls also pass an additional argument, of type PrintStream, where the method would write, which would make a test easier by passing a PrintStream which would write to a byte array.

Upvotes: 1

Smutje
Smutje

Reputation: 18143

You should break up your code into two methods - one prints the results of the second, and the second can be easily unit tested.

Upvotes: 2

Ashwinee K Jha
Ashwinee K Jha

Reputation: 9307

You can not obviously test if the method returns correct value if it is 'void'. However you can test whether it throws any exception or not. If you want to test the computation you need to refactor the code such that the computation is a separate method that returns a value.

Upvotes: 4

Related Questions