Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 263
user3331579 Avatar asked Jan 17 '26 23:01

user3331579


2 Answers

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.

like image 126
Ashwinee K Jha Avatar answered Jan 20 '26 16:01

Ashwinee K Jha


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

like image 35
Smutje Avatar answered Jan 20 '26 15:01

Smutje



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!