-
Notifications
You must be signed in to change notification settings - Fork 211
Testing cookbook
Victor Ng edited this page Mar 10, 2015
·
1 revision
You want to use two functions a lot. spy
and mock
.
mock
will generate an object instance that does nothing on any method invocation. spies are similar, but you can wrap an existing instance and overload the behavior of any method.
This is useful in particular with testing android UI code where you just want to no-op most of the object creation.
- In your View derived classes, you will want to minimize the length of the
onCreate
and related methods that are run during view life cycle. Try to push out as much code as possible into a delegate method so that it's easy to no-op that method with mockito.
A good example of this is in MapFragment and MapFragmentTest where the fragment has a doOnCreateView
method which is stubbed out with a no-op using mockito.doNothing
Look at org.mozilla.mozstumbler.service.stumblerthread.motiondetection.LegacyMotionSensorTest:
private long howLongUntilMotionSensorRun(long motionDetectDefaultPauseTimeMs, MotionSensor motionSensor) {
long i = ONE_SEC_MS;
for (; i < motionDetectDefaultPauseTimeMs + ONE_SEC_MS; i += ONE_SEC_MS) {
Robolectric.pauseMainLooper();
Robolectric.idleMainLooper(ONE_SEC_MS);
if (!motionSensor.mIsStartMotionSensorRunnableScheduled) {
break;
}
}
return i;
}
Asserting a toast:
ShadowHandler.idleMainLooper();
assertThat( ShadowToast.getTextOfLatestToast(), equalTo("Please enter a value."));