Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a method with return type void

I'm new to software testing. In a tutorial I read that I can test some methods like this:

@Test
 public void testMultiply() {
   MyClass tester = new MyClass();
   assertEquals("10 x 5 must be 50", 50, tester.multiply(10, 5));
 } 

So I have to pass some parameters to a method and get a return value.
But in my case I have some classes without any parameters and return values:

ArrayList al = new ArrayList();

public void Main(){
  methodA();
  methodB();
}

public void methodA(){
  // connect to URL
  // get some data
  for(int i=0; i<someThing; i++){
    al.add(data);
  }
}
public void methodB(){
  // do something with al
}

Is it also possible to test them? For example whether the right value comes from the URL in methodA().

like image 996
Evgenij Reznik Avatar asked Sep 19 '14 19:09

Evgenij Reznik


People also ask

How to unit test a method with void return type?

How to unit test a method with void return type? 1 save changes to the database 2 perform network call 3 any other type of external calls (send an email, call another service) If any of this represents your void method, then you will see how to test that method. ...

Why do we test void methods?

But it is also really important to understand why we test void methods. Whenever we write unit test cases for any method, we expect a return value from the method. Generally, we use assert for checking if the method returns the value that we expect it to return, but in the case of void methods, they do not return any value.

How do you test if a method returns a value?

Whenever we write unit test cases for any method, we expect a return value from the method. Generally, we use assert for checking if the method returns the value that we expect it to return, but in the case of void methods, they do not return any value.

Is it possible to test the void method in TDD?

Void method can be tested but you will need to look at the use of a mocking framework and some form of dependency injection. In TDD you should be developing the test before producing the code and therefore the test is defining what the code should do.


1 Answers

It is possible to test methods that don't return anything (void), but you must test that method's side effects. It should have some side effects, otherwise such a method is useless.

The side effect here is that al is changed. As written, this class doesn't have any other methods that expose al. Add a getter method that returns either the ArrayList or a specific element of the ArrayList. Then your test method can call the getter method to retrieve the value(s) and compare it(them) with the expected value(s).

like image 77
rgettman Avatar answered Oct 24 '22 16:10

rgettman