Reputation: 14897
In my Android JUnit test case, a LoaderTestCase
, I want to test if my Loader throws an exception or returns null. I am seeing that a NullPointerException
is thrown in the test, and the test is aborted.
I am trying to catch the exception like this:
try {
getLoaderResultSynchronously(new HistoricDataLoader(getContext(), url, username, password,
https, md5, station, stationMetaData, from, to));
// Expected exception wasn't thrown: fail.
fail();
} catch (NullPointerException e) {
// Expected exception was thrown. Success.
Log.e(TAG, e.getMessage());
}
But instead of catching the exception, the LoaderTestCase is aborting with the following exception:
java.lang.NullPointerException
at java.util.concurrent.ArrayBlockingQueue.checkNotNull(ArrayBlockingQueue.java:126)
at java.util.concurrent.ArrayBlockingQueue.offer(ArrayBlockingQueue.java:295)
at java.util.AbstractQueue.add(AbstractQueue.java:66)
at java.util.concurrent.ArrayBlockingQueue.add(ArrayBlockingQueue.java:282)
at android.test.LoaderTestCase$2.onLoadComplete(LoaderTestCase.java:70)
at android.content.Loader.deliverResult(Loader.java:144)
at android.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:265)
at android.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:92)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Can you tell me how I can
HistoricDataLoader#loadInBackground()
Edit:
I am aware of how to test for exceptions in JUnit 4. Right now I am doing my Android tests with JUnit 3, hence I catch them like shown in the code. If your answer is that I should use JUnit 4 instead of JUnit 3, please explain why that should make a difference.
The Exception is thrown and aborts the test inside the method getLoaderResultSynchronously()
. It is not passed up the calling chain, so I don't see how JUnit 4 should be able to catch it.
Upvotes: 1
Views: 174
Reputation: 355
In jUnit 4 you can expect Exceptions using annotations, your code could look something like this:
@Test(expected=NullPointerException.class)
public void loaderNpe() {
getLoaderResultSynchronously(new HistoricDataLoader(getContext(), url, username, password,vhttps, md5, station, stationMetaData, from, to));
}
Upvotes: 0