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()
.
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. ...
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With