Nimdokai Nimdokai - 11 days ago 5
Android Question

junit test assert with result after return;

Let assume that:

void someMethod(Context context, int a){
if(context==null || a == 0){
return;
}
...
}


Is it possible to somehow test that it has stopped on this if statement if it is not returning anything?
I mean, I would like to put some kind of assert that checked "okey, context was null, so it stopped on this return"

Of course the problem is related that the class is void and it may be questionable why I'd like to test this kind of sort of methods, but I'd like to hear about some possibilities.

Answer

If a method has no return value, all you can test for is:

  • State changes: whether there is an expected (or unexpected) state change of the instance on which you invoke someMethod, or context, or some other global state that might happen to be changed in the method.
  • Exceptions: if context is null, and you don't return here, you may get a NullPointerException or some other type of exception subsequently. But you don't really need to check for this explicitly, since the JUnit test would fail if one occurs that you don't expect (you just need to make sure that you're not accidentally swallowing that exception in your test).

And, ultimately, that's what you should be testing: test what the method does (state changes, exceptions thrown, return values (if you have one) etc), not how it does it (does it return on this line or that line).

Comments