我正在尝试对使用SharedPrefrences
的片段和活动进行一些单元测试,以及其他相关类别。但是,当我尝试像以下那样模拟这些时,我似乎总是会得到ClassNotFound
例外:
ClassNotFoundException: android.content.Context
这是一个示例:
我的" timerfragment"包含一个" mynotificationmanager"类。
@RunWith(MockitoJUnitRunner.class)
public class TimerFragmentUnitTest {
@Mock
TimerFragmentView view;
@Mock
MyNotificationManger notificationManger;
private TimerFragmentPresenter presenter;
@Before
public void setUp(){
presenter = new TimerFragmentPresenter(notificationManger);
presenter.bindView(view);
}
@Test
public void shouldSendNotification() throws Exception{
//Given
doNothing().when(view).setStopEnabled(false);
doNothing().when(view).setStopEnabled(true);
//When
presenter.setMinutesAndSeconds(2000);
TimeUnit.MILLISECONDS.sleep(3000);
//Then
verify(notificationManger,times(1)).sendTimerFinishNotification();
}
}
在此示例中,我遇到了ClassNotFoundException: android.content.Context
错误,因为MyNotificationManager
中有一个Context
对象。
任何建议都将不胜感激。
谢谢。
这是MyNotificationTimer
public class MyNotificationManger {
private static final String EXTRA_NOTIFICATION_TIMER = "notification_timer";
private static final int TIMER_NOTIFICATION_ID = 1;
private final Context _context;
public MyNotificationManger(Context context) {
_context = context;
}
public void sendTimerFinishNotification() {
int icon = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? R.mipmap.ic_launcher : R.drawable.methodegg;
Notification.Builder builder =
new Notification.Builder(_context)
.setSmallIcon(icon)
.setContentTitle(_context.getString(R.string.timer))
.setContentText(_context.getString(R.string.ready))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
.setAutoCancel(true);
Intent resultIntent = new Intent(_context, NavigationActivity.class);
resultIntent.putExtra(EXTRA_NOTIFICATION_TIMER, true);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
_context,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager) _context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(TIMER_NOTIFICATION_ID, builder.getNotification());
}
}
设法找到了答案,尽管Android文档似乎认为该解决方案应仅用作为'最后的度假胜地'。我把
android {
testOptions {
unitTests.returnDefaultValues = true
}
}
在顶级build.gradle
。
根据文档,如果我发现Bizare的'If you run a test that calls an API from the Android SDK that you do not mock'
,则应使用此功能,因为我没有遇到'Method ... not mocked'
错误,我正在获得'ClassNotFoundException'