method2testcases
stringlengths 118
3.08k
|
---|
### Question:
BaseRegisterActivity extends SecuredNativeSmartRegisterActivity implements BaseRegisterContract.View { @Override protected void setupViews() { } @Override boolean onCreateOptionsMenu(Menu menu); @Override void onBackPressed(); @Override void displaySyncNotification(); @Override void displayToast(int resourceId); @Override void displayToast(String message); @Override void displayShortToast(int resourceId); @Override abstract void startFormActivity(String formName, String entityId, Map<String, String> metaData); @Override abstract void startFormActivity(JSONObject form); void refreshList(final FetchStatus fetchStatus); @Override void onResume(); @Override void showProgressDialog(int titleIdentifier); @Override void hideProgressDialog(); Fragment findFragmentByPosition(int position); abstract List<String> getViewIdentifiers(); @Override Context getContext(); void startQrCodeScanner(); @Override void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults); void switchToFragment(final int position); @Override void updateInitialsText(String initials); void switchToBaseFragment(); void setSelectedBottomBarMenuItem(int itemId); void setSearchTerm(String searchTerm); static int BASE_REG_POSITION; static int ADVANCED_SEARCH_POSITION; static int SORT_FILTER_POSITION; static int LIBRARY_POSITION; static int ME_POSITION; }### Answer:
@Test public void testSetupViewsDoesNothing() { activity = spy(activity); activity.setupViews(); verify(activity).setupViews(); verifyNoMoreInteractions(activity); } |
### Question:
BaseRegisterActivity extends SecuredNativeSmartRegisterActivity implements BaseRegisterContract.View { @Override protected void onResumption() { presenter.registerViewConfigurations(getViewIdentifiers()); } @Override boolean onCreateOptionsMenu(Menu menu); @Override void onBackPressed(); @Override void displaySyncNotification(); @Override void displayToast(int resourceId); @Override void displayToast(String message); @Override void displayShortToast(int resourceId); @Override abstract void startFormActivity(String formName, String entityId, Map<String, String> metaData); @Override abstract void startFormActivity(JSONObject form); void refreshList(final FetchStatus fetchStatus); @Override void onResume(); @Override void showProgressDialog(int titleIdentifier); @Override void hideProgressDialog(); Fragment findFragmentByPosition(int position); abstract List<String> getViewIdentifiers(); @Override Context getContext(); void startQrCodeScanner(); @Override void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults); void switchToFragment(final int position); @Override void updateInitialsText(String initials); void switchToBaseFragment(); void setSelectedBottomBarMenuItem(int itemId); void setSearchTerm(String searchTerm); static int BASE_REG_POSITION; static int ADVANCED_SEARCH_POSITION; static int SORT_FILTER_POSITION; static int LIBRARY_POSITION; static int ME_POSITION; }### Answer:
@Test public void testOnResumption() { activity.onResumption(); verify(activity.presenter).registerViewConfigurations(null); } |
### Question:
BaseRegisterActivity extends SecuredNativeSmartRegisterActivity implements BaseRegisterContract.View { @Override protected void onInitialization() { } @Override boolean onCreateOptionsMenu(Menu menu); @Override void onBackPressed(); @Override void displaySyncNotification(); @Override void displayToast(int resourceId); @Override void displayToast(String message); @Override void displayShortToast(int resourceId); @Override abstract void startFormActivity(String formName, String entityId, Map<String, String> metaData); @Override abstract void startFormActivity(JSONObject form); void refreshList(final FetchStatus fetchStatus); @Override void onResume(); @Override void showProgressDialog(int titleIdentifier); @Override void hideProgressDialog(); Fragment findFragmentByPosition(int position); abstract List<String> getViewIdentifiers(); @Override Context getContext(); void startQrCodeScanner(); @Override void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults); void switchToFragment(final int position); @Override void updateInitialsText(String initials); void switchToBaseFragment(); void setSelectedBottomBarMenuItem(int itemId); void setSearchTerm(String searchTerm); static int BASE_REG_POSITION; static int ADVANCED_SEARCH_POSITION; static int SORT_FILTER_POSITION; static int LIBRARY_POSITION; static int ME_POSITION; }### Answer:
@Test public void testOnInitializationDoesNothing() { activity = spy(activity); activity.onInitialization(); verify(activity).onInitialization(); verifyNoMoreInteractions(activity); } |
### Question:
BaseRegisterActivity extends SecuredNativeSmartRegisterActivity implements BaseRegisterContract.View { @Override public void onResume() { super.onResume(); if (bottomNavigationView != null && bottomNavigationView.getSelectedItemId() != R.id.action_clients) { setSelectedBottomBarMenuItem(R.id.action_clients); } } @Override boolean onCreateOptionsMenu(Menu menu); @Override void onBackPressed(); @Override void displaySyncNotification(); @Override void displayToast(int resourceId); @Override void displayToast(String message); @Override void displayShortToast(int resourceId); @Override abstract void startFormActivity(String formName, String entityId, Map<String, String> metaData); @Override abstract void startFormActivity(JSONObject form); void refreshList(final FetchStatus fetchStatus); @Override void onResume(); @Override void showProgressDialog(int titleIdentifier); @Override void hideProgressDialog(); Fragment findFragmentByPosition(int position); abstract List<String> getViewIdentifiers(); @Override Context getContext(); void startQrCodeScanner(); @Override void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults); void switchToFragment(final int position); @Override void updateInitialsText(String initials); void switchToBaseFragment(); void setSelectedBottomBarMenuItem(int itemId); void setSearchTerm(String searchTerm); static int BASE_REG_POSITION; static int ADVANCED_SEARCH_POSITION; static int SORT_FILTER_POSITION; static int LIBRARY_POSITION; static int ME_POSITION; }### Answer:
@Test public void testOnResumeSelectsClientsIfNotSelected() { BottomNavigationView bottomNavigationView = activity.bottomNavigationView; bottomNavigationView.setSelectedItemId(R.id.action_search); activity.onResume(); assertEquals(R.id.action_clients, bottomNavigationView.getSelectedItemId()); } |
### Question:
BaseRegisterActivity extends SecuredNativeSmartRegisterActivity implements BaseRegisterContract.View { @Override public void showProgressDialog(int titleIdentifier) { progressDialog = new ProgressDialog(this); progressDialog.setCancelable(false); progressDialog.setTitle(titleIdentifier); progressDialog.setMessage(getString(R.string.please_wait_message)); if (!isFinishing()) progressDialog.show(); } @Override boolean onCreateOptionsMenu(Menu menu); @Override void onBackPressed(); @Override void displaySyncNotification(); @Override void displayToast(int resourceId); @Override void displayToast(String message); @Override void displayShortToast(int resourceId); @Override abstract void startFormActivity(String formName, String entityId, Map<String, String> metaData); @Override abstract void startFormActivity(JSONObject form); void refreshList(final FetchStatus fetchStatus); @Override void onResume(); @Override void showProgressDialog(int titleIdentifier); @Override void hideProgressDialog(); Fragment findFragmentByPosition(int position); abstract List<String> getViewIdentifiers(); @Override Context getContext(); void startQrCodeScanner(); @Override void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults); void switchToFragment(final int position); @Override void updateInitialsText(String initials); void switchToBaseFragment(); void setSelectedBottomBarMenuItem(int itemId); void setSearchTerm(String searchTerm); static int BASE_REG_POSITION; static int ADVANCED_SEARCH_POSITION; static int SORT_FILTER_POSITION; static int LIBRARY_POSITION; static int ME_POSITION; }### Answer:
@Test public void testShowProgressDialog() { activity.showProgressDialog(R.string.form_back_confirm_dialog_message); ProgressDialog progressDialog = Whitebox.getInternalState(activity, "progressDialog"); assertTrue(progressDialog.isShowing()); } |
### Question:
BaseRegisterActivity extends SecuredNativeSmartRegisterActivity implements BaseRegisterContract.View { @Override public void hideProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); } } @Override boolean onCreateOptionsMenu(Menu menu); @Override void onBackPressed(); @Override void displaySyncNotification(); @Override void displayToast(int resourceId); @Override void displayToast(String message); @Override void displayShortToast(int resourceId); @Override abstract void startFormActivity(String formName, String entityId, Map<String, String> metaData); @Override abstract void startFormActivity(JSONObject form); void refreshList(final FetchStatus fetchStatus); @Override void onResume(); @Override void showProgressDialog(int titleIdentifier); @Override void hideProgressDialog(); Fragment findFragmentByPosition(int position); abstract List<String> getViewIdentifiers(); @Override Context getContext(); void startQrCodeScanner(); @Override void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults); void switchToFragment(final int position); @Override void updateInitialsText(String initials); void switchToBaseFragment(); void setSelectedBottomBarMenuItem(int itemId); void setSearchTerm(String searchTerm); static int BASE_REG_POSITION; static int ADVANCED_SEARCH_POSITION; static int SORT_FILTER_POSITION; static int LIBRARY_POSITION; static int ME_POSITION; }### Answer:
@Test public void testHideProgressDialog() { activity.showProgressDialog(R.string.form_back_confirm_dialog_message); ProgressDialog progressDialog = Whitebox.getInternalState(activity, "progressDialog"); assertTrue(progressDialog.isShowing()); activity.hideProgressDialog(); assertFalse(progressDialog.isShowing()); } |
### Question:
BaseRegisterActivity extends SecuredNativeSmartRegisterActivity implements BaseRegisterContract.View { @Override protected void onStop() { super.onStop(); presenter.unregisterViewConfiguration(getViewIdentifiers()); } @Override boolean onCreateOptionsMenu(Menu menu); @Override void onBackPressed(); @Override void displaySyncNotification(); @Override void displayToast(int resourceId); @Override void displayToast(String message); @Override void displayShortToast(int resourceId); @Override abstract void startFormActivity(String formName, String entityId, Map<String, String> metaData); @Override abstract void startFormActivity(JSONObject form); void refreshList(final FetchStatus fetchStatus); @Override void onResume(); @Override void showProgressDialog(int titleIdentifier); @Override void hideProgressDialog(); Fragment findFragmentByPosition(int position); abstract List<String> getViewIdentifiers(); @Override Context getContext(); void startQrCodeScanner(); @Override void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults); void switchToFragment(final int position); @Override void updateInitialsText(String initials); void switchToBaseFragment(); void setSelectedBottomBarMenuItem(int itemId); void setSearchTerm(String searchTerm); static int BASE_REG_POSITION; static int ADVANCED_SEARCH_POSITION; static int SORT_FILTER_POSITION; static int LIBRARY_POSITION; static int ME_POSITION; }### Answer:
@Test public void testStop() { activity.onStop(); verify(activity.presenter).unregisterViewConfiguration(null); } |
### Question:
BaseRegisterActivity extends SecuredNativeSmartRegisterActivity implements BaseRegisterContract.View { @Override public Context getContext() { return this; } @Override boolean onCreateOptionsMenu(Menu menu); @Override void onBackPressed(); @Override void displaySyncNotification(); @Override void displayToast(int resourceId); @Override void displayToast(String message); @Override void displayShortToast(int resourceId); @Override abstract void startFormActivity(String formName, String entityId, Map<String, String> metaData); @Override abstract void startFormActivity(JSONObject form); void refreshList(final FetchStatus fetchStatus); @Override void onResume(); @Override void showProgressDialog(int titleIdentifier); @Override void hideProgressDialog(); Fragment findFragmentByPosition(int position); abstract List<String> getViewIdentifiers(); @Override Context getContext(); void startQrCodeScanner(); @Override void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults); void switchToFragment(final int position); @Override void updateInitialsText(String initials); void switchToBaseFragment(); void setSelectedBottomBarMenuItem(int itemId); void setSearchTerm(String searchTerm); static int BASE_REG_POSITION; static int ADVANCED_SEARCH_POSITION; static int SORT_FILTER_POSITION; static int LIBRARY_POSITION; static int ME_POSITION; }### Answer:
@Test public void testGetContext() { assertEquals(activity, activity.getContext()); } |
### Question:
BaseRegisterActivity extends SecuredNativeSmartRegisterActivity implements BaseRegisterContract.View { @Override public void updateInitialsText(String initials) { this.userInitials = initials; } @Override boolean onCreateOptionsMenu(Menu menu); @Override void onBackPressed(); @Override void displaySyncNotification(); @Override void displayToast(int resourceId); @Override void displayToast(String message); @Override void displayShortToast(int resourceId); @Override abstract void startFormActivity(String formName, String entityId, Map<String, String> metaData); @Override abstract void startFormActivity(JSONObject form); void refreshList(final FetchStatus fetchStatus); @Override void onResume(); @Override void showProgressDialog(int titleIdentifier); @Override void hideProgressDialog(); Fragment findFragmentByPosition(int position); abstract List<String> getViewIdentifiers(); @Override Context getContext(); void startQrCodeScanner(); @Override void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults); void switchToFragment(final int position); @Override void updateInitialsText(String initials); void switchToBaseFragment(); void setSelectedBottomBarMenuItem(int itemId); void setSearchTerm(String searchTerm); static int BASE_REG_POSITION; static int ADVANCED_SEARCH_POSITION; static int SORT_FILTER_POSITION; static int LIBRARY_POSITION; static int ME_POSITION; }### Answer:
@Test public void testUpdateInitialsText() { activity.updateInitialsText("SG"); assertEquals("SG", activity.userInitials); } |
### Question:
BaseRegisterActivity extends SecuredNativeSmartRegisterActivity implements BaseRegisterContract.View { public void setSearchTerm(String searchTerm) { mBaseFragment.setSearchTerm(searchTerm); } @Override boolean onCreateOptionsMenu(Menu menu); @Override void onBackPressed(); @Override void displaySyncNotification(); @Override void displayToast(int resourceId); @Override void displayToast(String message); @Override void displayShortToast(int resourceId); @Override abstract void startFormActivity(String formName, String entityId, Map<String, String> metaData); @Override abstract void startFormActivity(JSONObject form); void refreshList(final FetchStatus fetchStatus); @Override void onResume(); @Override void showProgressDialog(int titleIdentifier); @Override void hideProgressDialog(); Fragment findFragmentByPosition(int position); abstract List<String> getViewIdentifiers(); @Override Context getContext(); void startQrCodeScanner(); @Override void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults); void switchToFragment(final int position); @Override void updateInitialsText(String initials); void switchToBaseFragment(); void setSelectedBottomBarMenuItem(int itemId); void setSearchTerm(String searchTerm); static int BASE_REG_POSITION; static int ADVANCED_SEARCH_POSITION; static int SORT_FILTER_POSITION; static int LIBRARY_POSITION; static int ME_POSITION; }### Answer:
@Test public void testSetSearchTerm() { Whitebox.setInternalState(activity, "mBaseFragment", fragment); activity.setSearchTerm("Doe"); verify(fragment).setSearchTerm("Doe"); } |
### Question:
BaseLoginActivity extends MultiLanguageActivity implements BaseLoginContract.View, TextView.OnEditorActionListener, View.OnClickListener { @Override public void enableLoginButton(boolean isClickable) { loginButton.setClickable(isClickable); } @Override boolean onCreateOptionsMenu(Menu menu); @Override boolean onOptionsItemSelected(MenuItem item); @Override void onDestroy(); EditText getPasswordEditText(); @Override void showErrorDialog(String message); void showErrorDialog(@StringRes int title, String message); void showErrorDialog(String title, String message); void showProgress(final boolean show); @Override void hideKeyboard(); @Override void enableLoginButton(boolean isClickable); @Override boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent); @Override void onClick(View v); @Override void setUsernameError(int resourceId); @Override void resetUsernameError(); @Override void setPasswordError(int resourceId); @Override void resetPaswordError(); @Override Activity getActivityContext(); @Override AppCompatActivity getAppCompatActivity(); @Override void updateProgressMessage(String message); @Override boolean isAppVersionAllowed(); @Override void showClearDataDialog(@NonNull DialogInterface.OnClickListener onClickListener); String getAuthTokenType(); boolean isNewAccount(); }### Answer:
@Test public void enableLoginButtonShouldMakeLoginBtnClickable() { boolean isClickable = false; baseLoginActivity.enableLoginButton(isClickable); Button btn = ReflectionHelpers.getField(baseLoginActivity, "loginButton"); Assert.assertFalse(btn.isClickable()); } |
### Question:
BaseLoginActivity extends MultiLanguageActivity implements BaseLoginContract.View, TextView.OnEditorActionListener, View.OnClickListener { @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add("Settings"); return true; } @Override boolean onCreateOptionsMenu(Menu menu); @Override boolean onOptionsItemSelected(MenuItem item); @Override void onDestroy(); EditText getPasswordEditText(); @Override void showErrorDialog(String message); void showErrorDialog(@StringRes int title, String message); void showErrorDialog(String title, String message); void showProgress(final boolean show); @Override void hideKeyboard(); @Override void enableLoginButton(boolean isClickable); @Override boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent); @Override void onClick(View v); @Override void setUsernameError(int resourceId); @Override void resetUsernameError(); @Override void setPasswordError(int resourceId); @Override void resetPaswordError(); @Override Activity getActivityContext(); @Override AppCompatActivity getAppCompatActivity(); @Override void updateProgressMessage(String message); @Override boolean isAppVersionAllowed(); @Override void showClearDataDialog(@NonNull DialogInterface.OnClickListener onClickListener); String getAuthTokenType(); boolean isNewAccount(); }### Answer:
@Test public void onCreateOptionsShouldReturnTrueAndPopulateMenu() { Menu menu = Mockito.mock(Menu.class); Assert.assertTrue(baseLoginActivity.onCreateOptionsMenu(menu)); Mockito.verify(menu).add(Mockito.eq("Settings")); } |
### Question:
BaseLoginActivity extends MultiLanguageActivity implements BaseLoginContract.View, TextView.OnEditorActionListener, View.OnClickListener { @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getTitle().toString().equalsIgnoreCase("Settings")) { startActivity(new Intent(this, SettingsActivity.class)); return true; } return super.onOptionsItemSelected(item); } @Override boolean onCreateOptionsMenu(Menu menu); @Override boolean onOptionsItemSelected(MenuItem item); @Override void onDestroy(); EditText getPasswordEditText(); @Override void showErrorDialog(String message); void showErrorDialog(@StringRes int title, String message); void showErrorDialog(String title, String message); void showProgress(final boolean show); @Override void hideKeyboard(); @Override void enableLoginButton(boolean isClickable); @Override boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent); @Override void onClick(View v); @Override void setUsernameError(int resourceId); @Override void resetUsernameError(); @Override void setPasswordError(int resourceId); @Override void resetPaswordError(); @Override Activity getActivityContext(); @Override AppCompatActivity getAppCompatActivity(); @Override void updateProgressMessage(String message); @Override boolean isAppVersionAllowed(); @Override void showClearDataDialog(@NonNull DialogInterface.OnClickListener onClickListener); String getAuthTokenType(); boolean isNewAccount(); }### Answer:
@Test public void onOptionsItemSelectedShouldReturnTrueAndCallStartActivityWhenSettingsIsClicked() { MenuItem menuItem = Mockito.mock(MenuItem.class); Mockito.doReturn("Settings").when(menuItem).getTitle(); Assert.assertTrue(baseLoginActivity.onOptionsItemSelected(menuItem)); Intent intent = Shadows.shadowOf(baseLoginActivity).peekNextStartedActivity(); Assert.assertEquals(SettingsActivity.class.getName(), intent.getComponent().getClassName()); } |
### Question:
BaseLoginActivity extends MultiLanguageActivity implements BaseLoginContract.View, TextView.OnEditorActionListener, View.OnClickListener { @Override public void onDestroy() { super.onDestroy(); mLoginPresenter.onDestroy(isChangingConfigurations()); } @Override boolean onCreateOptionsMenu(Menu menu); @Override boolean onOptionsItemSelected(MenuItem item); @Override void onDestroy(); EditText getPasswordEditText(); @Override void showErrorDialog(String message); void showErrorDialog(@StringRes int title, String message); void showErrorDialog(String title, String message); void showProgress(final boolean show); @Override void hideKeyboard(); @Override void enableLoginButton(boolean isClickable); @Override boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent); @Override void onClick(View v); @Override void setUsernameError(int resourceId); @Override void resetUsernameError(); @Override void setPasswordError(int resourceId); @Override void resetPaswordError(); @Override Activity getActivityContext(); @Override AppCompatActivity getAppCompatActivity(); @Override void updateProgressMessage(String message); @Override boolean isAppVersionAllowed(); @Override void showClearDataDialog(@NonNull DialogInterface.OnClickListener onClickListener); String getAuthTokenType(); boolean isNewAccount(); }### Answer:
@Test public void onDestroyShouldCallPresenterOnDestroy() { baseLoginActivity.onDestroy(); Mockito.verify(baseLoginActivity.mLoginPresenter).onDestroy(Mockito.eq(false)); } |
### Question:
BaseLoginActivity extends MultiLanguageActivity implements BaseLoginContract.View, TextView.OnEditorActionListener, View.OnClickListener { @Override public boolean isAppVersionAllowed() { boolean isAppVersionAllowed = true; try { isAppVersionAllowed = syncUtils.isAppVersionAllowed(); } catch (PackageManager.NameNotFoundException e) { Timber.e(e); } return isAppVersionAllowed; } @Override boolean onCreateOptionsMenu(Menu menu); @Override boolean onOptionsItemSelected(MenuItem item); @Override void onDestroy(); EditText getPasswordEditText(); @Override void showErrorDialog(String message); void showErrorDialog(@StringRes int title, String message); void showErrorDialog(String title, String message); void showProgress(final boolean show); @Override void hideKeyboard(); @Override void enableLoginButton(boolean isClickable); @Override boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent); @Override void onClick(View v); @Override void setUsernameError(int resourceId); @Override void resetUsernameError(); @Override void setPasswordError(int resourceId); @Override void resetPaswordError(); @Override Activity getActivityContext(); @Override AppCompatActivity getAppCompatActivity(); @Override void updateProgressMessage(String message); @Override boolean isAppVersionAllowed(); @Override void showClearDataDialog(@NonNull DialogInterface.OnClickListener onClickListener); String getAuthTokenType(); boolean isNewAccount(); }### Answer:
@Test public void isAppVersionAllowedShouldReturnSyncUtilsValue() throws PackageManager.NameNotFoundException { SyncUtils syncUtils = Mockito.spy((SyncUtils) ReflectionHelpers.getField(baseLoginActivity, "syncUtils")); ReflectionHelpers.setField(baseLoginActivity, "syncUtils", syncUtils); Mockito.doReturn(false).when(syncUtils).isAppVersionAllowed(); Assert.assertFalse(baseLoginActivity.isAppVersionAllowed()); } |
### Question:
BaseLoginActivity extends MultiLanguageActivity implements BaseLoginContract.View, TextView.OnEditorActionListener, View.OnClickListener { public void showProgress(final boolean show) { if (!isFinishing()) { if (show) { progressDialog.show(); } else { progressDialog.dismiss(); } } } @Override boolean onCreateOptionsMenu(Menu menu); @Override boolean onOptionsItemSelected(MenuItem item); @Override void onDestroy(); EditText getPasswordEditText(); @Override void showErrorDialog(String message); void showErrorDialog(@StringRes int title, String message); void showErrorDialog(String title, String message); void showProgress(final boolean show); @Override void hideKeyboard(); @Override void enableLoginButton(boolean isClickable); @Override boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent); @Override void onClick(View v); @Override void setUsernameError(int resourceId); @Override void resetUsernameError(); @Override void setPasswordError(int resourceId); @Override void resetPaswordError(); @Override Activity getActivityContext(); @Override AppCompatActivity getAppCompatActivity(); @Override void updateProgressMessage(String message); @Override boolean isAppVersionAllowed(); @Override void showClearDataDialog(@NonNull DialogInterface.OnClickListener onClickListener); String getAuthTokenType(); boolean isNewAccount(); }### Answer:
@Test public void testShowProgressShouldExecuteWhenActivityIsActive() { baseLoginActivity.showProgress(true); ProgressDialog progressDialog = ReflectionHelpers.getField(baseLoginActivity, "progressDialog"); Assert.assertTrue(progressDialog.isShowing()); }
@Test public void testShowProgressShouldNotExecuteWhenActivityIsDestroyed() { ProgressDialog spyProgressDialog = Mockito.spy(new ProgressDialog(baseLoginActivity)); ReflectionHelpers.setField(baseLoginActivity, "progressDialog", spyProgressDialog); baseLoginActivity.finish(); baseLoginActivity.showProgress(true); Mockito.verify(spyProgressDialog, Mockito.never()).show(); } |
### Question:
BaseLoginActivity extends MultiLanguageActivity implements BaseLoginContract.View, TextView.OnEditorActionListener, View.OnClickListener { @Override public void updateProgressMessage(String message) { if (!isFinishing()) { progressDialog.setTitle(message); } } @Override boolean onCreateOptionsMenu(Menu menu); @Override boolean onOptionsItemSelected(MenuItem item); @Override void onDestroy(); EditText getPasswordEditText(); @Override void showErrorDialog(String message); void showErrorDialog(@StringRes int title, String message); void showErrorDialog(String title, String message); void showProgress(final boolean show); @Override void hideKeyboard(); @Override void enableLoginButton(boolean isClickable); @Override boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent); @Override void onClick(View v); @Override void setUsernameError(int resourceId); @Override void resetUsernameError(); @Override void setPasswordError(int resourceId); @Override void resetPaswordError(); @Override Activity getActivityContext(); @Override AppCompatActivity getAppCompatActivity(); @Override void updateProgressMessage(String message); @Override boolean isAppVersionAllowed(); @Override void showClearDataDialog(@NonNull DialogInterface.OnClickListener onClickListener); String getAuthTokenType(); boolean isNewAccount(); }### Answer:
@Test public void testUpdateProgressMessageShouldExecuteWhenActivityIsActive() { String msg = "text"; ProgressDialog spyProgressDialog = Mockito.spy(new ProgressDialog(baseLoginActivity)); ReflectionHelpers.setField(baseLoginActivity, "progressDialog", spyProgressDialog); baseLoginActivity.updateProgressMessage(msg); Mockito.verify(spyProgressDialog, Mockito.times(1)).setTitle(Mockito.eq(msg)); }
@Test public void testUpdateProgressMessageShouldNotExecuteWhenActivityIsDestroyed() { String msg = "text"; ProgressDialog spyProgressDialog = Mockito.spy(new ProgressDialog(baseLoginActivity)); ReflectionHelpers.setField(baseLoginActivity, "progressDialog", spyProgressDialog); baseLoginActivity.finish(); baseLoginActivity.updateProgressMessage(msg); Mockito.verify(spyProgressDialog, Mockito.never()).setTitle(Mockito.eq(msg)); } |
### Question:
SecuredActivity extends MultiLanguageActivity implements P2pProcessingStatusBroadcastReceiver.StatusUpdate { protected abstract void onCreation(); @Override boolean onOptionsItemSelected(MenuItem item); @Override boolean onCreateOptionsMenu(Menu menu); void startFormActivity(String formName, String entityId, String metaData); void startFormActivity(String formName, String entityId, Map<String, String> metaData); void startMicroFormActivity(String formName, String entityId, String metaData); void replicationComplete(); void replicationError(); void showToast(String message); void showProcessingInProgressSnackbar(@NonNull AppCompatActivity appCompatActivity, int margin); void showProcessingInProgressBottomSnackbar(final @NonNull AppCompatActivity appCompatActivity); void removeProcessingInProgressSnackbar(); @Override void onStatusUpdate(boolean isProcessing); static final String LOG_TAG; }### Answer:
@Test public void onCreateShouldCallOnCreationAndAddLogoutListener() { List<WeakReference<Listener<Boolean>>> listeners = ReflectionHelpers.getField(Event.ON_LOGOUT, "listeners"); listeners.clear(); controller = Robolectric.buildActivity(SecuredActivityImpl.class); SecuredActivityImpl spyActivity = Mockito.spy((SecuredActivityImpl) ReflectionHelpers.getField(controller, "component")); ReflectionHelpers.setField(controller, "component", spyActivity); securedActivity = controller.get(); ReflectionHelpers.callInstanceMethod(Activity.class, securedActivity, "performCreate", from(Bundle.class, null)); Mockito.verify(securedActivity).onCreation(); listeners = ReflectionHelpers.getField(Event.ON_LOGOUT, "listeners"); Assert.assertEquals(1, listeners.size()); } |
### Question:
SecuredActivity extends MultiLanguageActivity implements P2pProcessingStatusBroadcastReceiver.StatusUpdate { @Override public boolean onOptionsItemSelected(MenuItem item) { int i = item.getItemId(); if (i == R.id.switchLanguageMenuItem) { String newLanguagePreference = context().userService().switchLanguagePreference(); Utils.showShortToast(this, getString(R.string.language_change_prepend_message) + " " + newLanguagePreference + "."); return super.onOptionsItemSelected(item); } else if (i == MENU_ITEM_LOGOUT) { DrishtiApplication application = (DrishtiApplication) getApplication(); application.logoutCurrentUser(); return super.onOptionsItemSelected(item); } else { return super.onOptionsItemSelected(item); } } @Override boolean onOptionsItemSelected(MenuItem item); @Override boolean onCreateOptionsMenu(Menu menu); void startFormActivity(String formName, String entityId, String metaData); void startFormActivity(String formName, String entityId, Map<String, String> metaData); void startMicroFormActivity(String formName, String entityId, String metaData); void replicationComplete(); void replicationError(); void showToast(String message); void showProcessingInProgressSnackbar(@NonNull AppCompatActivity appCompatActivity, int margin); void showProcessingInProgressBottomSnackbar(final @NonNull AppCompatActivity appCompatActivity); void removeProcessingInProgressSnackbar(); @Override void onStatusUpdate(boolean isProcessing); static final String LOG_TAG; }### Answer:
@Test public void onOptionsItemSelectedShouldLogoutUserWhenLogoutIsClicked() { MenuItem menuItem = Mockito.mock(MenuItem.class); Mockito.doReturn(securedActivity.MENU_ITEM_LOGOUT).when(menuItem).getItemId(); TestP2pApplication testP2pApplication = Mockito.spy((TestP2pApplication) securedActivity.getApplication()); Mockito.doReturn(testP2pApplication).when(securedActivity).getApplication(); Assert.assertFalse(securedActivity.onOptionsItemSelected(menuItem)); Mockito.verify(testP2pApplication).logoutCurrentUser(); } |
### Question:
SecuredActivity extends MultiLanguageActivity implements P2pProcessingStatusBroadcastReceiver.StatusUpdate { public void removeProcessingInProgressSnackbar() { if (processingInProgressSnackbar != null && processingInProgressSnackbar.isShown()) { processingInProgressSnackbar.dismiss(); } } @Override boolean onOptionsItemSelected(MenuItem item); @Override boolean onCreateOptionsMenu(Menu menu); void startFormActivity(String formName, String entityId, String metaData); void startFormActivity(String formName, String entityId, Map<String, String> metaData); void startMicroFormActivity(String formName, String entityId, String metaData); void replicationComplete(); void replicationError(); void showToast(String message); void showProcessingInProgressSnackbar(@NonNull AppCompatActivity appCompatActivity, int margin); void showProcessingInProgressBottomSnackbar(final @NonNull AppCompatActivity appCompatActivity); void removeProcessingInProgressSnackbar(); @Override void onStatusUpdate(boolean isProcessing); static final String LOG_TAG; }### Answer:
@Test public void removeProcessingInProgressSnackbarShouldDismissSnackbarWhenSnackbarIsShowing() { ProcessingInProgressSnackbar snackbar = Mockito.mock(ProcessingInProgressSnackbar.class); ReflectionHelpers.setField(securedActivity, "processingInProgressSnackbar", snackbar); Mockito.doReturn(true).when(snackbar).isShown(); securedActivity.removeProcessingInProgressSnackbar(); Mockito.verify(snackbar).dismiss(); } |
### Question:
BarcodeScanActivity extends Activity implements Detector.Processor<Barcode> { public void closeBarcodeActivity(SparseArray<Barcode> sparseArray) { Intent intent = new Intent(); if (sparseArray != null) { intent.putExtra(AllConstants.BARCODE.BARCODE_KEY, sparseArray.valueAt(0)); } setResult(RESULT_OK, intent); finish(); } @Override void release(); @Override void receiveDetections(Detector.Detections<Barcode> detections); void closeBarcodeActivity(SparseArray<Barcode> sparseArray); void startCameraSource(); }### Answer:
@Test public void testCloseActivitySuccessfully() { barcodeScanActivity.closeBarcodeActivity(barcodeSparseArray); Assert.assertTrue(barcodeScanActivity.isFinishing()); } |
### Question:
BarcodeScanActivity extends Activity implements Detector.Processor<Barcode> { @Override public void receiveDetections(Detector.Detections<Barcode> detections) { final SparseArray<Barcode> barcodeSparseArray = detections.getDetectedItems(); if (barcodeSparseArray.size() > 0) { Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(VIBRATOR_SERVICE); assert vibrator != null; vibrator.vibrate(100); closeBarcodeActivity(barcodeSparseArray); } } @Override void release(); @Override void receiveDetections(Detector.Detections<Barcode> detections); void closeBarcodeActivity(SparseArray<Barcode> sparseArray); void startCameraSource(); }### Answer:
@Test public void testReceiveDetections() { Assert.assertNotNull(detections); Mockito.doReturn(barcodeSparseArray).when(detections).getDetectedItems(); Assert.assertNotNull(barcodeSparseArray); Assert.assertEquals(0, barcodeSparseArray.size()); Mockito.doReturn(2).when(barcodeSparseArray).size(); Assert.assertEquals(2, barcodeSparseArray.size()); barcodeScanActivity.receiveDetections(detections); verify(barcodeScanActivity).closeBarcodeActivity(Mockito.eq(barcodeSparseArray)); } |
### Question:
DrishtiApplication extends Application { public static OpenSRPImageLoader getCachedImageLoaderInstance() { if (cachedImageLoader == null) { cachedImageLoader = new OpenSRPImageLoader( DrishtiApplication.getInstance().getApplicationContext(), R.drawable.woman_placeholder).setFadeInImage((Build.VERSION.SDK_INT >= 12)); } return cachedImageLoader; } static synchronized X getInstance(); @Nullable P2PClassifier<JSONObject> getP2PClassifier(); static BitmapImageCache getMemoryCacheInstance(); static String getAppDir(); static OpenSRPImageLoader getCachedImageLoaderInstance(); @Override void onCreate(); void initializeCrashLyticsTree(); abstract void logoutCurrentUser(); Repository getRepository(); CredentialsHelper credentialsProvider(); final byte[] getPassword(); void setPassword(byte[] password); @NonNull ClientProcessorForJava getClientProcessor(); String getUsername(); @Override void onTerminate(); Context getContext(); }### Answer:
@Test public void getCachedImageLoaderInstance() { drishtiApplication.onCreate(); Assert.assertNull(ReflectionHelpers.getStaticField(DrishtiApplication.class, "cachedImageLoader")); Assert.assertNotNull(DrishtiApplication.getCachedImageLoaderInstance()); } |
### Question:
DrishtiApplication extends Application { public Repository getRepository() { ArrayList<DrishtiRepository> drishtiRepositoryList = CoreLibrary.getInstance().context().sharedRepositories(); DrishtiRepository[] drishtiRepositoryArray = drishtiRepositoryList.toArray(new DrishtiRepository[drishtiRepositoryList.size()]); if (repository == null) { repository = new Repository(getInstance().getApplicationContext(), null, drishtiRepositoryArray); } return repository; } static synchronized X getInstance(); @Nullable P2PClassifier<JSONObject> getP2PClassifier(); static BitmapImageCache getMemoryCacheInstance(); static String getAppDir(); static OpenSRPImageLoader getCachedImageLoaderInstance(); @Override void onCreate(); void initializeCrashLyticsTree(); abstract void logoutCurrentUser(); Repository getRepository(); CredentialsHelper credentialsProvider(); final byte[] getPassword(); void setPassword(byte[] password); @NonNull ClientProcessorForJava getClientProcessor(); String getUsername(); @Override void onTerminate(); Context getContext(); }### Answer:
@Test public void getRepository() { drishtiApplication.onCreate(); Assert.assertNull(ReflectionHelpers.getField(drishtiApplication, "repository")); Assert.assertNotNull(drishtiApplication.getRepository()); } |
### Question:
DrishtiApplication extends Application { public final byte[] getPassword() { if (password == null) { password = credentialsProvider().getCredentials(getUsername(), CredentialsHelper.CREDENTIALS_TYPE.DB_AUTH); } return password; } static synchronized X getInstance(); @Nullable P2PClassifier<JSONObject> getP2PClassifier(); static BitmapImageCache getMemoryCacheInstance(); static String getAppDir(); static OpenSRPImageLoader getCachedImageLoaderInstance(); @Override void onCreate(); void initializeCrashLyticsTree(); abstract void logoutCurrentUser(); Repository getRepository(); CredentialsHelper credentialsProvider(); final byte[] getPassword(); void setPassword(byte[] password); @NonNull ClientProcessorForJava getClientProcessor(); String getUsername(); @Override void onTerminate(); Context getContext(); }### Answer:
@Test public void getPassword() { byte[] password = "pwd".getBytes(); drishtiApplication.onCreate(); Assert.assertNull(ReflectionHelpers.getField(drishtiApplication, "password")); CredentialsHelper credentialsProvider = Mockito.spy(new CredentialsHelper(Mockito.mock(Context.class))); Mockito.doReturn(password).when(credentialsProvider).getCredentials(ArgumentMatchers.anyString(), ArgumentMatchers.eq(CredentialsHelper.CREDENTIALS_TYPE.DB_AUTH)); ReflectionHelpers.setField(drishtiApplication, "credentialsHelper", credentialsProvider); Assert.assertEquals(password, drishtiApplication.getPassword()); } |
### Question:
PregnancyDetails { public boolean isLastMonthOfPregnancy() { return isLastMonthOfPregnancy; } PregnancyDetails(String monthsPregnantArg, String eddArg, int daysPastEddArg); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean isLastMonthOfPregnancy(); }### Answer:
@Test public void isLastMonthOfPregnancy() throws Exception { PregnancyDetails pregnancyDetails = new PregnancyDetails("8", magicDate, 0); Assert.assertTrue(pregnancyDetails.isLastMonthOfPregnancy()); pregnancyDetails = new PregnancyDetails("7", magicDate, 0); Assert.assertFalse(pregnancyDetails.isLastMonthOfPregnancy()); } |
### Question:
SmartRegisterClients extends ArrayList<SmartRegisterClient> { public SmartRegisterClients applyFilterWithFP(final ServiceModeOption serviceModeOption, SortOption sortOption, final FilterOption... filterOptions) { SmartRegisterClients results = new SmartRegisterClients(); Iterables.addAll(results, Iterables.filter(this, new Predicate<SmartRegisterClient>() { @Override public boolean apply(SmartRegisterClient client) { boolean isClientToBeFiltered = true; for (FilterOption filterOption : filterOptions) { isClientToBeFiltered = isClientToBeFiltered && filterOption.filter(client); } return isClientToBeFiltered; } })); serviceModeOption.apply(); return sortOption.sort(results); } SmartRegisterClients applyFilter(final FilterOption villageFilter, final
ServiceModeOption serviceModeOption, final FilterOption searchFilter, SortOption sortOption); SmartRegisterClients applyFilterWithFP(final ServiceModeOption serviceModeOption,
SortOption sortOption, final FilterOption...
filterOptions); }### Answer:
@Test public void shouldReturnFilteredListForFP() { SmartRegisterClients originalClients = getFPSmartRegisterClientsWithProperDetails(); SmartRegisterClients filteredClients = originalClients.applyFilterWithFP(fpAllMethodsServiceMode, new NameSort(), new FPMethodFilter("condom")); Assert.assertEquals(2, filteredClients.size()); Assert.assertEquals("Akshara", filteredClients.get(0).name()); Assert.assertEquals("Bhagya", filteredClients.get(1).name()); } |
### Question:
AbstractDao { public static SimpleDateFormat getDobDateFormat() { if (DOB_DATE_FORMAT == null) DOB_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); return DOB_DATE_FORMAT; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); }### Answer:
@Test public void testGetDateFormat() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date now = new Date(); Assert.assertEquals(sdf.format(now), AbstractDao.getDobDateFormat().format(now)); } |
### Question:
AbstractDao { public static SimpleDateFormat getNativeFormsDateFormat() { if (NATIVE_FORMS_DATE_FORMAT == null) NATIVE_FORMS_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); return NATIVE_FORMS_DATE_FORMAT; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); }### Answer:
@Test public void testGetNativeFormsDateFormat() { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date now = new Date(); Assert.assertEquals(sdf.format(now), AbstractDao.getNativeFormsDateFormat().format(now)); } |
### Question:
AbstractDao { protected static void setRepository(Repository repository) { AbstractDao.repository = repository; } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); }### Answer:
@Test public void testObjectsConstructedEqualsCursorSize() { MatrixCursor cursor = new MatrixCursor(new String[]{"count"}); cursor.addRow(new Object[]{"1"}); Mockito.doReturn(cursor).when(sqLiteDatabase).rawQuery(Mockito.anyString(), Mockito.any(String[].class)); SampleAbstractDaoImp.setRepository(repository); int count = SampleAbstractDaoImp.getCountOfEvents(); Assert.assertEquals(count, 1); }
@Test public void testErrorInSerializationReturnsNull() { MatrixCursor cursor = new MatrixCursor(new String[]{"count"}); cursor.addRow(new Object[]{"1"}); Mockito.doReturn(cursor).when(sqLiteDatabase).rawQuery(Mockito.anyString(), Mockito.any(String[].class)); SampleAbstractDaoImp.setRepository(repository); List<Alert> alerts = SampleAbstractDaoImp.getAllAlerts(); Assert.assertNull(alerts); } |
### Question:
AbstractDao { protected static void updateDB(String sql) { try { SQLiteDatabase db = getRepository().getWritableDatabase(); db.rawExecSQL(sql); } catch (Exception e) { Timber.e(e); } } static SimpleDateFormat getDobDateFormat(); static SimpleDateFormat getNativeFormsDateFormat(); static @Nullable List<Map<String, Object>> readData(String query, String[] selectionArgs); }### Answer:
@Test public void testUpdateDB() { String sql = "update table set col1 = 'value' where id = x"; AbstractDao.setRepository(repository); AbstractDao.updateDB(sql); Mockito.verify(sqLiteDatabase).rawExecSQL(sql); } |
### Question:
SmartRegisterPaginatedAdapter extends BaseAdapter { public int pageCount() { return pageCount; } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); void refreshClients(SmartRegisterClients filteredClients); @Override int getCount(); @Override Object getItem(int i); @Override long getItemId(int i); @Override View getView(int i, View parentView, ViewGroup viewGroup); int pageCount(); int currentPage(); void nextPage(); void previousPage(); boolean hasNextPage(); boolean hasPreviousPage(); void refreshList(FilterOption villageFilter, ServiceModeOption serviceModeOption,
FilterOption searchFilter, SortOption sortOption); SmartRegisterClientsProvider getListItemProvider(); }### Answer:
@Test public void assertshouldReturn3PageCountFor50Clients() { SmartRegisterPaginatedAdapter adapter = getAdapterWithFakeClients(FIFTY); Assert.assertEquals(adapter.pageCount(), THREE); } |
### Question:
SmartRegisterPaginatedAdapter extends BaseAdapter { @Override public Object getItem(int i) { return filteredClients.get(i); } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); void refreshClients(SmartRegisterClients filteredClients); @Override int getCount(); @Override Object getItem(int i); @Override long getItemId(int i); @Override View getView(int i, View parentView, ViewGroup viewGroup); int pageCount(); int currentPage(); void nextPage(); void previousPage(); boolean hasNextPage(); boolean hasPreviousPage(); void refreshList(FilterOption villageFilter, ServiceModeOption serviceModeOption,
FilterOption searchFilter, SortOption sortOption); SmartRegisterClientsProvider getListItemProvider(); }### Answer:
@Test public void assertgetItemShouldReturnRespectiveItem() { SmartRegisterPaginatedAdapter adapter = getAdapterWithFakeClients(FIFTY); Assert.assertEquals(((ECClient) adapter.getItem(ZERO)).name(), NameZERO); Assert.assertEquals(((ECClient) adapter.getItem(FOURTYNINE)).name(), NameFOURTYNINE); } |
### Question:
SmartRegisterPaginatedAdapter extends BaseAdapter { @Override public View getView(int i, View parentView, ViewGroup viewGroup) { return listItemProvider .getView((SmartRegisterClient) getItem(actualPosition(i)), parentView, viewGroup); } SmartRegisterPaginatedAdapter(SmartRegisterClientsProvider listItemProvider); SmartRegisterPaginatedAdapter(int clientsPerPage, SmartRegisterClientsProvider
listItemProvider); void refreshClients(SmartRegisterClients filteredClients); @Override int getCount(); @Override Object getItem(int i); @Override long getItemId(int i); @Override View getView(int i, View parentView, ViewGroup viewGroup); int pageCount(); int currentPage(); void nextPage(); void previousPage(); boolean hasNextPage(); boolean hasPreviousPage(); void refreshList(FilterOption villageFilter, ServiceModeOption serviceModeOption,
FilterOption searchFilter, SortOption sortOption); SmartRegisterClientsProvider getListItemProvider(); }### Answer:
@Test public void assertgetViewShouldDelegateCallToProviderGetViewWithProperClient() { FakeClientsProvider fakeClientsProvider = new FakeClientsProvider(getSmartRegisterClients(FIFTY)); SmartRegisterPaginatedAdapter adapter = getAdapter(fakeClientsProvider); adapter.getView(ZERO, null, null); Assert.assertEquals(NameZERO, fakeClientsProvider.getViewCurrentClient.name()); adapter.getView(FOURTYNINE, null, null); Assert.assertEquals(NameFOURTYNINE, fakeClientsProvider.getViewCurrentClient.name()); } |
### Question:
ServiceLocationsAdapter extends BaseAdapter { @Override public int getCount() { return locationNames.size(); } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); }### Answer:
@Test public void testGetCount() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); Assert.assertEquals(adapter.getCount(), 3); } |
### Question:
ServiceLocationsAdapter extends BaseAdapter { @Override public long getItemId(int position) { return position + 2321; } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); }### Answer:
@Test public void testGetItemId() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); Assert.assertEquals(adapter.getItemId(0), 2321); } |
### Question:
ServiceLocationsAdapter extends BaseAdapter { public String getLocationAt(int position) { return locationNames.get(position); } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); }### Answer:
@Test public void testGetLocationAt() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); Assert.assertEquals(adapter.getLocationAt(0), "test1"); } |
### Question:
ServiceLocationsAdapter extends BaseAdapter { public List<String> getLocationNames() { return locationNames; } ServiceLocationsAdapter(Context context, List<String> locationNames); @Override int getCount(); @Override Object getItem(int position); @Override long getItemId(int position); @Override View getView(int position, View convertView, ViewGroup parent); void setSelectedLocation(final String locationName); String getLocationAt(int position); List<String> getLocationNames(); }### Answer:
@Test public void testGetLocationNames() { ServiceLocationsAdapter adapter = getAdapterWithFakeClients(); List<String> names = adapter.getLocationNames(); Assert.assertEquals(names.get(0), "test1"); } |
### Question:
IntegerUtil { public static int compare(int lhs, int rhs) { return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1); } static Integer tryParse(String value, int defaultValue); static String tryParse(String value, String defaultValue); static int compare(int lhs, int rhs); }### Answer:
@Test public void assertIntegerCompareReturnsInt() { Assert.assertEquals(IntegerUtil.compare(1, 2), -1); Assert.assertEquals(IntegerUtil.compare(2, 2), 0); Assert.assertEquals(IntegerUtil.compare(3, 2), 1); } |
### Question:
SyncTaskServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } SyncTaskServiceJob(Class<? extends SyncTaskIntentService> serviceClass); static final String TAG; }### Answer:
@Test public void testOnRunJobStartsCorrectService() { SyncTaskServiceJob syncTaskServiceJob = new SyncTaskServiceJob(SyncTaskIntentService.class); SyncTaskServiceJob syncTaskServiceJobSpy = Mockito.spy(syncTaskServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(syncTaskServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); syncTaskServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.SyncTaskIntentService", intent.getValue().getComponent().getClassName()); } |
### Question:
ValidateSyncDataServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ValidateIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; }### Answer:
@Test public void testOnRunJobStartsCorrectService() { ValidateSyncDataServiceJob validateSyncDataServiceJob = new ValidateSyncDataServiceJob(); ValidateSyncDataServiceJob validateSyncDataServiceJobSpy = Mockito.spy(validateSyncDataServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(validateSyncDataServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); validateSyncDataServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.ValidateIntentService", intent.getValue().getComponent().getClassName()); } |
### Question:
CampaignServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), CampaignIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; }### Answer:
@Test public void testOnRunJobStartsCorrectService() { CampaignServiceJob campaignServiceJob = new CampaignServiceJob(); CampaignServiceJob campaignServiceJobJobSpy = Mockito.spy(campaignServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(campaignServiceJobJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); campaignServiceJobJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.CampaignIntentService", intent.getValue().getComponent().getClassName()); } |
### Question:
PullUniqueIdsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), PullUniqueIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; }### Answer:
@Test public void testOnRunJobStartsCorrectService() { PullUniqueIdsServiceJob pullUniqueIdsServiceJob = new PullUniqueIdsServiceJob(); PullUniqueIdsServiceJob pullUniqueIdsServiceJobSpy = Mockito.spy(pullUniqueIdsServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(pullUniqueIdsServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); pullUniqueIdsServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.PullUniqueIdsIntentService", intent.getValue().getComponent().getClassName()); } |
### Question:
ExtendedSyncServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), ExtendedSyncIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; }### Answer:
@Test public void testOnRunJobStartsCorrectService() { ExtendedSyncServiceJob extendedSyncServiceJob = new ExtendedSyncServiceJob(); ExtendedSyncServiceJob syncServiceJobSpy = Mockito.spy(extendedSyncServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(syncServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); syncServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.ExtendedSyncIntentService", intent.getValue().getComponent().getClassName()); } |
### Question:
SyncLocationsByLevelAndTagsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByLevelAndTagsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; }### Answer:
@Test public void testOnRunJobStartsCorrectService() { SyncLocationsByLevelAndTagsServiceJob syncLocationsByLevelAndTagsServiceJob = new SyncLocationsByLevelAndTagsServiceJob(); SyncLocationsByLevelAndTagsServiceJob syncLocationsByLevelAndTagsServiceJobSpy = Mockito.spy(syncLocationsByLevelAndTagsServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(syncLocationsByLevelAndTagsServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); syncLocationsByLevelAndTagsServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.SyncLocationsByLevelAndTagsIntentService", intent.getValue().getComponent().getClassName()); } |
### Question:
DocumentConfigurationServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } DocumentConfigurationServiceJob(Class<? extends DocumentConfigurationIntentService> serviceClass); static final String TAG; }### Answer:
@Test public void testOnRunJobStartsCorrectService() { DocumentConfigurationServiceJob documentConfigurationServiceJob = new DocumentConfigurationServiceJob(DocumentConfigurationIntentService.class); DocumentConfigurationServiceJob documentConfigurationServiceJobSpy = Mockito.spy(documentConfigurationServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(documentConfigurationServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); documentConfigurationServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.DocumentConfigurationIntentService", intent.getValue().getComponent().getClassName()); } |
### Question:
SyncServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), serviceClass); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } SyncServiceJob(Class<? extends SyncIntentService> serviceClass); static final String TAG; }### Answer:
@Test public void testOnRunJobStartsCorrectService() { SyncServiceJob syncServiceJob = new SyncServiceJob(SyncIntentService.class); SyncServiceJob syncServiceJobSpy = Mockito.spy(syncServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(syncServiceJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); syncServiceJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.SyncIntentService", intent.getValue().getComponent().getClassName()); } |
### Question:
SyncLocationsByTeamIdsJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncLocationsByTeamIdsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; }### Answer:
@Test public void testOnRunJobStartsCorrectService() { SyncLocationsByTeamIdsJob syncLocationsByTeamIdsJob = new SyncLocationsByTeamIdsJob(); SyncLocationsByTeamIdsJob syncLocationsByTeamIdsJobSpy = Mockito.spy(syncLocationsByTeamIdsJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(syncLocationsByTeamIdsJobSpy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); syncLocationsByTeamIdsJobSpy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); Assert.assertEquals("org.smartregister.sync.intent.SyncLocationsByTeamIdsIntentService", intent.getValue().getComponent().getClassName()); } |
### Question:
SyncAllLocationsServiceJob extends BaseJob { @NonNull @Override protected Result onRunJob(@NonNull Params params) { Intent intent = new Intent(getApplicationContext(), SyncAllLocationsIntentService.class); getApplicationContext().startService(intent); return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; } static final String TAG; }### Answer:
@Test public void testOnRunJobStartsCorrectService() { SyncAllLocationsServiceJob syncAllLocationsServiceJob = new SyncAllLocationsServiceJob(); SyncAllLocationsServiceJob spy = Mockito.spy(syncAllLocationsServiceJob); ArgumentCaptor<Intent> intent = ArgumentCaptor.forClass(Intent.class); Mockito.doReturn(context).when(spy).getApplicationContext(); Mockito.doReturn(componentName).when(context).startService(ArgumentMatchers.any(Intent.class)); spy.onRunJob(null); Mockito.verify(context).startService(intent.capture()); assertEquals("org.smartregister.sync.intent.SyncAllLocationsIntentService", intent.getValue().getComponent().getClassName()); } |
### Question:
Campaign { public String getTitle() { return title; } String getIdentifier(); void setIdentifier(String identifier); String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); TaskStatus getStatus(); void setStatus(TaskStatus status); ExecutionPeriod getExecutionPeriod(); void setExecutionPeriod(ExecutionPeriod executionPeriod); DateTime getAuthoredOn(); void setAuthoredOn(DateTime authoredOn); DateTime getLastModified(); void setLastModified(DateTime lastModified); String getOwner(); void setOwner(String owner); long getServerVersion(); void setServerVersion(long serverVersion); }### Answer:
@Test public void testSerialize() { Campaign campaign = gson.fromJson(campaignJson, Campaign.class); assertEquals(campaignJson, gson.toJson(campaign)); assertEquals(campaign.getTitle(),"2019 IRS Season 1"); } |
### Question:
DateUtil { public static boolean checkIfDateThreeMonthsOlder(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(cal.getTime()); cal.add(Calendar.DATE, -90); Date dateBefore90Days = cal.getTime(); return date.before(dateBefore90Days); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); static String DEFAULT_DATE_FORMAT; static String DATE_FORMAT_FOR_TIMELINE_EVENT; }### Answer:
@Test public void assertCheckIfDateThreeMonthsOlderReturnsBoolean() { Assert.assertEquals(DateUtil.checkIfDateThreeMonthsOlder(new Date()), false); } |
### Question:
DateUtil { public static boolean isValidDate(String dateString) { if (dateString == null || dateString.length() != "yyyy-MM-dd".length()) { return false; } return dateString.matches("\\d{4}-\\d{2}-\\d{2}"); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); static String DEFAULT_DATE_FORMAT; static String DATE_FORMAT_FOR_TIMELINE_EVENT; }### Answer:
@Test public void assertIsVaidDateReturnsBoolean() { Assert.assertEquals(DateUtil.isValidDate(null), false); Assert.assertEquals(DateUtil.isValidDate("invaliddate"), false); Assert.assertEquals(DateUtil.isValidDate("2017-10-20"), true); } |
### Question:
ClientProcessor { public static ClientProcessor getInstance(Context context) { if (instance == null) { instance = new ClientProcessor(context); } return instance; } ClientProcessor(Context context); static ClientProcessor getInstance(Context context); synchronized void processClient(); synchronized void processClient(List<JSONObject> events); Boolean processEvent(JSONObject event, JSONObject clientClassificationJson); Boolean processEvent(JSONObject event, JSONObject client, JSONObject
clientClassificationJson); Boolean processClientClass(JSONObject clientClass, JSONObject event, JSONObject client); Boolean processField(JSONObject fieldJson, JSONObject event, JSONObject client); Boolean processAlert(JSONObject alert, JSONObject clientAlertClassificationJson); Boolean closeCase(JSONObject client, JSONArray closesCase); Boolean processCaseModel(JSONObject event, JSONObject client, JSONArray createsCase); void updateClientDetailsTable(JSONObject event, JSONObject client); void saveClientDetails(String baseEntityId, Map<String, String> values, Long timestamp); Map<String, String> getClientAddressAsMap(JSONObject client); Long executeInsertStatement(ContentValues values, String tableName); void closeCase(String tableName, String baseEntityId); boolean deleteCase(String tableName, String baseEntityId); void executeInsertAlert(ContentValues contentValues); JSONObject getColumnMappings(String registerName); void updateFTSsearch(String tableName, String entityId, ContentValues contentValues); void setCloudantDataHandler(CloudantDataHandler mCloudantDataHandler); Context getContext(); static final String baseEntityIdJSONKey; }### Answer:
@Test public void instantiatesSuccessfullyOnConstructorCall() throws Exception { Assert.assertNotNull(new ClientProcessor(context.applicationContext())); Assert.assertNotNull(ClientProcessor.getInstance(context.applicationContext())); } |
### Question:
P2pProcessRecordsService extends BaseSyncIntentService { @Override public void onDestroy() { if (CoreLibrary.getInstance().isPeerToPeerProcessing()) { CoreLibrary.getInstance().setPeerToPeerProcessing(false); } super.onDestroy(); } P2pProcessRecordsService(String name); P2pProcessRecordsService(); @Override void onDestroy(); }### Answer:
@Test public void onDestroyShouldSetPeerProcessingToFalse() { CoreLibrary.getInstance().setPeerToPeerProcessing(true); Assert.assertTrue(CoreLibrary.getInstance().isPeerToPeerProcessing()); p2pProcessRecordsService.onDestroy(); Assert.assertFalse(CoreLibrary.getInstance().isPeerToPeerProcessing()); } |
### Question:
SyncIntentService extends BaseSyncIntentService { protected void init(@NonNull Context context) { this.context = context; httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); syncUtils = new SyncUtils(getBaseContext()); validateAssignmentHelper = new ValidateAssignmentHelper(syncUtils); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; }### Answer:
@Test public void testInit() { assertNotNull(Whitebox.getInternalState(syncIntentService, "httpAgent")); assertNotNull(Whitebox.getInternalState(syncIntentService, "syncUtils")); assertNotNull(Whitebox.getInternalState(syncIntentService, "context")); } |
### Question:
SyncIntentService extends BaseSyncIntentService { protected void handleSync() { sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); doSync(); } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; }### Answer:
@Test public void testHandleSyncSendFetchStartedBroadCast() throws PackageManager.NameNotFoundException { syncIntentService = spy(syncIntentService); Whitebox.setInternalState(syncIntentService, "syncUtils", syncUtils); when(syncUtils.verifyAuthorization()).thenReturn(true); when(syncUtils.isAppVersionAllowed()).thenReturn(true); syncIntentService.handleSync(); verify(syncIntentService, times(2)).sendBroadcast(intentArgumentCaptor.capture()); assertEquals(SyncStatusBroadcastReceiver.ACTION_SYNC_STATUS, intentArgumentCaptor.getAllValues().get(0).getAction()); assertEquals(FetchStatus.fetchStarted, intentArgumentCaptor.getAllValues().get(0).getSerializableExtra(SyncStatusBroadcastReceiver.EXTRA_FETCH_STATUS)); }
@Test public void testHandleSyncCallsLogoutUserIfHasValidAuthorizationIsFalse() throws AuthenticatorException, OperationCanceledException, IOException { Whitebox.setInternalState(syncIntentService, "syncUtils", syncUtils); when(syncUtils.verifyAuthorization()).thenReturn(false); when(syncConfiguration.disableSyncToServerIfUserIsDisabled()).thenReturn(true); syncIntentService.handleSync(); verify(syncUtils).logoutUser(); }
@Test public void testHandleSyncCallsLogOutUserIfAppVersionIsNotAllowedAnd() throws AuthenticatorException, OperationCanceledException, IOException { syncIntentService = spy(syncIntentService); Whitebox.setInternalState(syncIntentService, "syncUtils", syncUtils); when(syncUtils.verifyAuthorization()).thenReturn(true); when(syncConfiguration.disableSyncToServerIfUserIsDisabled()).thenReturn(true); syncIntentService.handleSync(); verify(syncUtils).logoutUser(); } |
### Question:
DateUtil { public static int weekDifference(LocalDate startDate, LocalDate endDate) { try { return Math.abs(Weeks.weeksBetween(startDate, endDate).getWeeks()); } catch (Exception e) { return 0; } } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); static String DEFAULT_DATE_FORMAT; static String DATE_FORMAT_FOR_TIMELINE_EVENT; }### Answer:
@Test public void assertWeekDifferenceReturnsInt() { LocalDate start = new LocalDate(1447487308000l); LocalDate end = new LocalDate(1510645708000l); Assert.assertEquals(DateUtil.weekDifference(start, end), 104); } |
### Question:
SyncIntentService extends BaseSyncIntentService { public void fetchFailed(int count) { if (count < CoreLibrary.getInstance().getSyncConfiguration().getSyncMaxRetries()) { int newCount = count + 1; fetchRetry(newCount, false); } else { complete(FetchStatus.fetchedFailed); } } SyncIntentService(); SyncIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); void fetchFailed(int count); int getEventPullLimit(); HTTPAgent getHttpAgent(); Context getContext(); static final String SYNC_URL; }### Answer:
@Test public void testFetchFailedWithCountLessThanMaxSyncRetryCallsFetchRetry() { when(syncConfiguration.getSyncMaxRetries()).thenReturn(1); initMocksForPullECFromServerUsingPOST(); syncIntentService = spy(syncIntentService); ResponseStatus responseStatus = ResponseStatus.failure; Mockito.doReturn(new Response<>(responseStatus, null)) .when(httpAgent).postWithJsonResponse(stringArgumentCaptor.capture(), stringArgumentCaptor.capture()); syncIntentService.fetchFailed(0); verify(syncIntentService).fetchFailed(1); } |
### Question:
DocumentConfigurationIntentService extends BaseSyncIntentService { @Override public int onStartCommand(Intent intent, int flags, int startId) { httpAgent = CoreLibrary.getInstance().context().getHttpAgent(); manifestRepository = CoreLibrary.getInstance().context().getManifestRepository(); clientFormRepository = CoreLibrary.getInstance().context().getClientFormRepository(); configuration = CoreLibrary.getInstance().context().configuration(); return super.onStartCommand(intent, flags, startId); } DocumentConfigurationIntentService(); DocumentConfigurationIntentService(String name); @Override int onStartCommand(Intent intent, int flags, int startId); }### Answer:
@Test public void onStartCommandShouldInstantiateVariables() { Assert.assertNull(ReflectionHelpers.getField(documentConfigurationIntentService, "httpAgent")); Assert.assertNull(ReflectionHelpers.getField(documentConfigurationIntentService, "manifestRepository")); Assert.assertNull(ReflectionHelpers.getField(documentConfigurationIntentService, "clientFormRepository")); Assert.assertNull(ReflectionHelpers.getField(documentConfigurationIntentService, "configuration")); documentConfigurationIntentService.onStartCommand(null, 0, 900); Assert.assertNotNull(ReflectionHelpers.getField(documentConfigurationIntentService, "httpAgent")); Assert.assertNotNull(ReflectionHelpers.getField(documentConfigurationIntentService, "manifestRepository")); Assert.assertNotNull(ReflectionHelpers.getField(documentConfigurationIntentService, "clientFormRepository")); Assert.assertNotNull(ReflectionHelpers.getField(documentConfigurationIntentService, "configuration")); } |
### Question:
DateUtil { public static String formatDate(String unformattedDate) { return formatDate(unformattedDate, DEFAULT_DATE_FORMAT); } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); static String DEFAULT_DATE_FORMAT; static String DATE_FORMAT_FOR_TIMELINE_EVENT; }### Answer:
@Test public void formatDateTest() { Assert.assertEquals("03-10-2019", DateUtil.formatDate(new LocalDate("2019-10-03"), "dd-MM-YYY")); Assert.assertEquals("", DateUtil.formatDate(new LocalDate("2019-10-03"), "KK-TT")); } |
### Question:
SettingsSyncIntentService extends BaseSyncIntentService { protected boolean processSettings(Intent intent) { Timber.d("In Settings Sync Intent Service..."); boolean isSuccessfulSync = true; if (intent != null) { try { super.onHandleIntent(intent); int count = syncSettingsServiceHelper.processIntent(); if (count > 0) { intent.putExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, count); } } catch (JSONException e) { isSuccessfulSync = false; logError(TAG + " Error fetching client settings"); } } return isSuccessfulSync; } SettingsSyncIntentService(); @Override void onCreate(); static final String SETTINGS_URL; static final String EVENT_SYNC_COMPLETE; }### Answer:
@Test public void processSettingsShouldReturnTrueWhenIntentIsNull() throws JSONException { settingsSyncIntentService.syncSettingsServiceHelper = Mockito.spy(settingsSyncIntentService.syncSettingsServiceHelper); Assert.assertTrue(settingsSyncIntentService.processSettings(null)); Mockito.verify(settingsSyncIntentService.syncSettingsServiceHelper, Mockito.never()).processIntent(); }
@Test public void processSettingsShouldReturnTrueAndCallProcessIntentWhenIntentIsNotNull() throws JSONException { settingsSyncIntentService.syncSettingsServiceHelper = Mockito.spy(settingsSyncIntentService.syncSettingsServiceHelper); Mockito.doReturn(30).when(settingsSyncIntentService.syncSettingsServiceHelper).processIntent(); Intent intent = new Intent(); Assert.assertTrue(settingsSyncIntentService.processSettings(intent)); Mockito.verify(settingsSyncIntentService.syncSettingsServiceHelper, Mockito.times(1)).processIntent(); Assert.assertEquals(30, intent.getIntExtra(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, 0)); } |
### Question:
SettingsSyncIntentService extends BaseSyncIntentService { @Override public void onCreate() { super.onCreate(); Context context = CoreLibrary.getInstance().context(); syncSettingsServiceHelper = new SyncSettingsServiceHelper(context.configuration().dristhiBaseURL(), context.getHttpAgent()); } SettingsSyncIntentService(); @Override void onCreate(); static final String SETTINGS_URL; static final String EVENT_SYNC_COMPLETE; }### Answer:
@Test public void onCreateShouldCreateSyncSettingsServiceHelper() { settingsSyncIntentService = Robolectric.buildIntentService(SettingsSyncIntentService.class) .get(); Assert.assertNull(settingsSyncIntentService.syncSettingsServiceHelper); settingsSyncIntentService.onCreate(); Assert.assertNotNull(settingsSyncIntentService.syncSettingsServiceHelper); } |
### Question:
TaskServiceHelper extends BaseHelper { public List<Task> syncTasks() { syncCreatedTaskToServer(); syncTaskStatusToServer(); return fetchTasksFromServer(); } @VisibleForTesting TaskServiceHelper(TaskRepository taskRepository); void setSyncByGroupIdentifier(boolean syncByGroupIdentifier); boolean isSyncByGroupIdentifier(); static TaskServiceHelper getInstance(); List<Task> syncTasks(); List<Task> fetchTasksFromServer(); void syncTaskStatusToServer(); void syncCreatedTaskToServer(); static final String TASK_LAST_SYNC_DATE; static final String UPDATE_STATUS_URL; static final String ADD_TASK_URL; static final String SYNC_TASK_URL; static final Gson taskGson; }### Answer:
@Test public void testSyncTasks() { taskServiceHelper.syncTasks(); verify(taskServiceHelper).syncCreatedTaskToServer(); verify(taskServiceHelper).syncTaskStatusToServer(); } |
### Question:
PlanIntentServiceHelper extends BaseHelper { public void syncPlans() { syncProgress = new SyncProgress(); syncProgress.setSyncEntity(SyncEntity.PLANS); syncProgress.setTotalRecords(totalRecords); int batchFetchCount = batchFetchPlansFromServer(true); syncProgress.setPercentageSynced(Utils.calculatePercentage(totalRecords, batchFetchCount)); sendSyncProgressBroadcast(syncProgress, context); } private PlanIntentServiceHelper(PlanDefinitionRepository planRepository, LocationRepository locationRepository); static PlanIntentServiceHelper getInstance(); void syncPlans(); static final String SYNC_PLANS_URL; static final String PLAN_LAST_SYNC_DATE; }### Answer:
@Test public void testSyncPlansCallsSendSyncProgressDialog() { Whitebox.setInternalState(planIntentServiceHelper, "totalRecords", 10l); planIntentServiceHelper.syncPlans(); verify(planIntentServiceHelper).sendSyncProgressBroadcast(syncProgressArgumentCaptor.capture(),any()); assertEquals(SyncEntity.PLANS, syncProgressArgumentCaptor.getValue().getSyncEntity()); assertEquals(10l, syncProgressArgumentCaptor.getValue().getTotalRecords()); assertEquals(0, syncProgressArgumentCaptor.getValue().getPercentageSynced()); } |
### Question:
DateUtil { public static LocalDate getLocalDate(String date) { try { SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_FORMAT, Utils.getDefaultLocale()); Date formattedDate = format.parse(date); return new LocalDate(formattedDate); } catch (Exception e) { return null; } } static void fakeIt(LocalDate fakeDayAsToday); static void setDefaultDateFormat(String defaultDateFormat); static LocalDate today(); static String formatDateForTimelineEvent(String unformattedDate); static String formatDate(String unformattedDate); static String formatDate(String date, String pattern); static String formatDate(LocalDate date, String pattern); static String formatFromISOString(String date, String pattern); static LocalDate getLocalDate(String date); static LocalDate getLocalDateFromISOString(String date); static int dayDifference(LocalDate startDate, LocalDate endDate); static int weekDifference(LocalDate startDate, LocalDate endDate); static boolean isValidDate(String dateString); static String getDuration(DateTime dateTime); static String getDuration(Context context, DateTime dateTime); static String getDuration(long timeDiff); static String getDuration(long timeDiff, Locale locale); static boolean checkIfDateThreeMonthsOlder(Date date); static Long getMillis(DateTime dateTime); static Long getMillis(LocalDate localDate); static DateTime getDateTimeFromMillis(Long milliSeconds); static LocalDate getDateFromMillis(Long milliSeconds); static String DEFAULT_DATE_FORMAT; static String DATE_FORMAT_FOR_TIMELINE_EVENT; }### Answer:
@Test public void getLocalDateTest() { Assert.assertEquals(new LocalDate("2019-10-03"), DateUtil.getLocalDate("03/10/2019")); Assert.assertEquals(null, DateUtil.getLocalDate("03-15-2019")); } |
### Question:
ECSyncHelper { public boolean saveAllClientsAndEvents(JSONObject jsonObject) { try { if (jsonObject == null) { return false; } JSONArray events = jsonObject.has("events") ? jsonObject.getJSONArray("events") : new JSONArray(); JSONArray clients = jsonObject.has("clients") ? jsonObject.getJSONArray("clients") : new JSONArray(); batchSave(events, clients); return true; } catch (Exception e) { Timber.e(e); return false; } } @VisibleForTesting protected ECSyncHelper(Context context, EventClientRepository eventClientRepository); static ECSyncHelper getInstance(Context context); boolean saveAllClientsAndEvents(JSONObject jsonObject); List<EventClient> allEventClients(long startSyncTimeStamp, long lastSyncTimeStamp); long getLastSyncTimeStamp(); void updateLastSyncTimeStamp(long lastSyncTimeStamp); void updateLastCheckTimeStamp(long lastCheckTimeStamp); long getLastCheckTimeStamp(); void batchSave(JSONArray events, JSONArray clients); List<EventClient> getEvents(Date lastSyncDate, String syncStatus); List<EventClient> getEvents(List<String> formSubmissionIds); JSONObject getClient(String baseEntityId); void addClient(String baseEntityId, JSONObject jsonObject); void addEvent(String baseEntityId, JSONObject jsonObject); void addEvent(String baseEntityId, JSONObject jsonObject, String syncStatus); List<EventClient> allEvents(long startSyncTimeStamp, long lastSyncTimeStamp); void batchInsertClients(JSONArray clients); void batchInsertEvents(JSONArray events); T convert(JSONObject jo, Class<T> t); JSONObject convertToJson(Object object); boolean deleteClient(String baseEntityId); }### Answer:
@Test public void testSaveAllClientsAndEventsShouldReturnFalseForNullParam() throws Exception { ECSyncHelper syncHelperSpy = Mockito.spy(syncHelper); boolean result = syncHelperSpy.saveAllClientsAndEvents(null); Assert.assertFalse(result); } |
### Question:
FileUtilities { public void write(String fileName, String data) { File root = Environment.getExternalStorageDirectory(); File outDir = new File(root.getAbsolutePath() + File.separator + "EZ_time_tracker"); if (!outDir.isDirectory()) { outDir.mkdir(); } try { if (!outDir.isDirectory()) { throw new IOException("Unable to create directory EZ_time_tracker. Maybe the SD " + "card is mounted?"); } File outputFile = new File(outDir, fileName); writer = new BufferedWriter(new FileWriter(outputFile)); writer.write(data); writer.close(); } catch (IOException e) { Timber.w(e); } } FileUtilities(); static Bitmap retrieveStaticImageFromDisk(String fileName); static String getFileExtension(String fileName); static String getUserAgent(Context mContext); static String getImageUrl(String entityID); void write(String fileName, String data); Writer getWriter(); String getAbsolutePath(); }### Answer:
@Test public void assertWriteWritesSuccessfully() throws Exception { String testData = "string to write"; when(Environment.getExternalStorageDirectory()).thenReturn(existentDirectory); PowerMockito.whenNew(BufferedWriter.class).withAnyArguments().thenReturn(mockWriter); FileUtilities fileUtils = new FileUtilities(); try { fileUtils.write(FILE_NAME, testData); String path = existentDirectory.getPath() + File.separator + "EZ_time_tracker" + File.separator + FILE_NAME; File file = new File(path); final String writenText = FileUtils.readFileToString(file); Assert.assertEquals(testData, writenText); } catch (Exception e) { Assert.fail(); } } |
### Question:
LocationServiceHelper extends BaseHelper { public List<Location> fetchLocationsStructures() { syncLocationsStructures(true); List<Location> locations = syncLocationsStructures(false); syncCreatedStructureToServer(); syncUpdatedLocationsToServer(); return locations; } LocationServiceHelper(LocationRepository locationRepository, LocationTagRepository locationTagRepository, StructureRepository structureRepository); static LocationServiceHelper getInstance(); List<Location> fetchLocationsStructures(); void fetchLocationsByLevelAndTags(); SyncConfiguration getSyncConfiguration(); void syncCreatedStructureToServer(); void syncUpdatedLocationsToServer(); void fetchOpenMrsLocationsByTeamIds(); HTTPAgent getHttpAgent(); @NotNull String getFormattedBaseUrl(); void fetchAllLocations(); static final String LOCATION_STRUCTURE_URL; static final String CREATE_STRUCTURE_URL; static final String COMMON_LOCATIONS_SERVICE_URL; static final String OPENMRS_LOCATION_BY_TEAM_IDS; static final String STRUCTURES_LAST_SYNC_DATE; static final String LOCATION_LAST_SYNC_DATE; static Gson locationGson; }### Answer:
@Test public void testFetchLocationsStructures() { locationServiceHelper.fetchLocationsStructures(); verify(locationServiceHelper).syncLocationsStructures(true); verify(locationServiceHelper).syncLocationsStructures(false); verify(locationServiceHelper).syncCreatedStructureToServer(); verify(locationServiceHelper).syncCreatedStructureToServer(); } |
### Question:
FileUtilities { public static String getFileExtension(String fileName) { String extension = ""; if (fileName != null && !fileName.isEmpty()) { int i = fileName.lastIndexOf('.'); if (i > 0) { extension = fileName.substring(i + 1); } } return extension; } FileUtilities(); static Bitmap retrieveStaticImageFromDisk(String fileName); static String getFileExtension(String fileName); static String getUserAgent(Context mContext); static String getImageUrl(String entityID); void write(String fileName, String data); Writer getWriter(); String getAbsolutePath(); }### Answer:
@Test public void assertReturnsCorrectFileExtension() { Assert.assertEquals(FileUtilities.getFileExtension(FILE_NAME), "txt"); } |
### Question:
GZIPCompression implements ICompression { @Override public byte[] compress(String rawString) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(os); gos.write(rawString.getBytes(CharEncoding.UTF_8)); gos.close(); byte[] compressed = os.toByteArray(); os.close(); return compressed; } catch (IOException e) { Timber.e(e); return null; } } @Override byte[] compress(String rawString); @Override String decompress(byte[] compressedBytes); @Override void compress(String inputFilePath, String compressedOutputFilepath); @Override void decompress(String compressedInputFilePath, String decompressedOutputFilePath); }### Answer:
@Test public void testCompressMethodReturnsACompressedOutput() throws IOException { byte[] original = TEST_STRING.getBytes(CharEncoding.UTF_8); byte[] compressed = gzipCompression.compress(TEST_STRING); Assert.assertTrue(original.length > compressed.length); }
@Test public void testCompressFileMethodReturnsACompressedOutputFile() throws IOException { String filePath = getFilePath("compression_test_file.txt"); String outputFilePath = filePath + "_compressed.gz"; File originalFile = new File(filePath); Assert.assertTrue(originalFile.length() > 0); File compressedFile = new File(outputFilePath); Assert.assertEquals(0, compressedFile.length()); gzipCompression.compress(filePath, outputFilePath); Assert.assertTrue(compressedFile.length() > 0); Assert.assertTrue(compressedFile.length() < originalFile.length()); } |
### Question:
DisplayUtils { public static int getDisplayWidth(Activity activity) { DisplayMetrics displayMetrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); return displayMetrics.widthPixels; } static ScreenDpi getScreenDpi(Context context); static int getDisplayWidth(Activity activity); static int getDisplayHeight(Activity activity); static double getScreenSize(Activity activity); }### Answer:
@Test public void testGetDisplayWidthReturnsCorrectWidthPixelsValue() { Mockito.doReturn(resources).when(context).getResources(); Mockito.doReturn(windowManager).when(context).getWindowManager(); DisplayManager displayManager = (DisplayManager) RuntimeEnvironment.application.getSystemService(Context.DISPLAY_SERVICE); Display display = displayManager.getDisplays()[0]; Mockito.doReturn(display).when(windowManager).getDefaultDisplay(); int defaultMetrics = display.getWidth(); int displayWidth = DisplayUtils.getDisplayWidth(context); Assert.assertTrue(displayWidth > 0); Assert.assertEquals(defaultMetrics, displayWidth); } |
### Question:
DisplayUtils { public static int getDisplayHeight(Activity activity) { DisplayMetrics displayMetrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); return displayMetrics.heightPixels; } static ScreenDpi getScreenDpi(Context context); static int getDisplayWidth(Activity activity); static int getDisplayHeight(Activity activity); static double getScreenSize(Activity activity); }### Answer:
@Test public void testGetDisplayHeightReturnsCorrectHeightPixelsValue() { Mockito.doReturn(resources).when(context).getResources(); Mockito.doReturn(windowManager).when(context).getWindowManager(); DisplayManager displayManager = (DisplayManager) RuntimeEnvironment.application.getSystemService(Context.DISPLAY_SERVICE); Display display = displayManager.getDisplays()[0]; Mockito.doReturn(display).when(windowManager).getDefaultDisplay(); int defaultMetrics = display.getHeight(); int displayHeight = DisplayUtils.getDisplayHeight(context); Assert.assertTrue(displayHeight > 0); Assert.assertEquals(defaultMetrics, displayHeight); } |
### Question:
DisplayUtils { public static double getScreenSize(Activity activity) { DisplayMetrics dm = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(dm); int width = dm.widthPixels; int height = dm.heightPixels; double wi = (double) width / (double) dm.xdpi; double hi = (double) height / (double) dm.ydpi; double x = Math.pow(wi, 2); double y = Math.pow(hi, 2); return Math.sqrt(x + y); } static ScreenDpi getScreenDpi(Context context); static int getDisplayWidth(Activity activity); static int getDisplayHeight(Activity activity); static double getScreenSize(Activity activity); }### Answer:
@Test public void testGetScreenSizeReturnsCorrectValues() { Mockito.doReturn(resources).when(context).getResources(); Mockito.doReturn(windowManager).when(context).getWindowManager(); DisplayManager displayManager = (DisplayManager) RuntimeEnvironment.application.getSystemService(Context.DISPLAY_SERVICE); Display display = displayManager.getDisplays()[0]; Mockito.doReturn(display).when(windowManager).getDefaultDisplay(); double screenSize = DisplayUtils.getScreenSize(context); Assert.assertEquals(3.5, screenSize, 0.1); } |
### Question:
CredentialsHelper { public static boolean shouldMigrate() { return CoreLibrary.getInstance().context().allSharedPreferences().getDBEncryptionVersion() == 0 || (CoreLibrary.getInstance().context().allSharedPreferences().getDBEncryptionVersion() > 0 && BuildConfig.DB_ENCRYPTION_VERSION > CoreLibrary.getInstance().context().allSharedPreferences().getDBEncryptionVersion()); } CredentialsHelper(Context context); static boolean shouldMigrate(); byte[] getCredentials(String username, String type); void saveCredentials(String type, String encryptedPassphrase); PasswordHash generateLocalAuthCredentials(char[] password); byte[] generateDBCredentials(char[] password, LoginResponseData userInfo); }### Answer:
@Test public void testShouldMigrateReturnsTrueForDBEncryptionVersionZero() { boolean shouldMigrate = CredentialsHelper.shouldMigrate(); Assert.assertTrue(shouldMigrate); } |
### Question:
ClientFormResponse { public ClientFormDTO getClientForm() { return clientForm; } ClientFormResponse(ClientFormDTO clientForm, ClientFormMetadataDTO clientFormMetadata); ClientFormDTO getClientForm(); void setClientForm(ClientFormDTO clientForm); ClientFormMetadataDTO getClientFormMetadata(); void setClientFormMetadata(ClientFormMetadataDTO clientFormMetadata); }### Answer:
@Test public void getClientForm() { ClientFormDTO clientFormDTO = new ClientFormDTO(); clientFormDTO.setId(1); clientFormDTO.setJson("[\"test json\"]"); ClientFormMetadataDTO clientFormMetadataDTO = new ClientFormMetadataDTO(); Date now = Calendar.getInstance().getTime(); clientFormMetadataDTO.setCreatedAt(now); clientFormMetadataDTO.setId(1L); clientFormMetadataDTO.setIdentifier("referral/anc_form"); clientFormMetadataDTO.setJurisdiction("test jurisdiction"); clientFormMetadataDTO.setLabel("ANC Referral form"); clientFormMetadataDTO.setModule("ANC"); clientFormMetadataDTO.setVersion("0.0.1"); ClientFormResponse clientFormResponse = new ClientFormResponse(clientFormDTO, clientFormMetadataDTO); Assert.assertEquals("referral/anc_form", clientFormResponse.getClientFormMetadata().getIdentifier()); Assert.assertEquals("test jurisdiction", clientFormResponse.getClientFormMetadata().getJurisdiction()); Assert.assertEquals("ANC Referral form", clientFormResponse.getClientFormMetadata().getLabel()); Assert.assertEquals("ANC", clientFormResponse.getClientFormMetadata().getModule()); Assert.assertEquals("0.0.1", clientFormResponse.getClientFormMetadata().getVersion()); Assert.assertEquals(now, clientFormResponse.getClientFormMetadata().getCreatedAt()); Assert.assertEquals(1, clientFormResponse.getClientForm().getId()); Assert.assertEquals("[\"test json\"]", clientFormResponse.getClientForm().getJson()); } |
### Question:
AllCommonsRepository { public long count() { return personRepository.count(); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void ShouldShowcount() throws Exception { when(personRepository.count()).thenReturn((long) 8); assertEquals(personRepository.count(), (long) 8); }
@Test public void testCount() { allCommonsRepository.count(); verify(personRepository).count(); } |
### Question:
CredentialsHelper { public byte[] getCredentials(String username, String type) { if (CREDENTIALS_TYPE.DB_AUTH.equals(type)) { return context.userService().getDecryptedPassphraseValue(username); } else if (CREDENTIALS_TYPE.LOCAL_AUTH.equals(type)) { return context.userService().getDecryptedAccountValue(username, AccountHelper.INTENT_KEY.ACCOUNT_LOCAL_PASSWORD); } return null; } CredentialsHelper(Context context); static boolean shouldMigrate(); byte[] getCredentials(String username, String type); void saveCredentials(String type, String encryptedPassphrase); PasswordHash generateLocalAuthCredentials(char[] password); byte[] generateDBCredentials(char[] password, LoginResponseData userInfo); }### Answer:
@Test public void testGetCredentialsInvokesGetDecryptedPassphraseValueWithCorrectValuesForDBAuth() { credentialsHelper.getCredentials(TEST_USERNAME, CredentialsHelper.CREDENTIALS_TYPE.DB_AUTH); ArgumentCaptor<String> usernameArgCaptor = ArgumentCaptor.forClass(String.class); Mockito.verify(userService, Mockito.times(1)).getDecryptedPassphraseValue(usernameArgCaptor.capture()); Assert.assertEquals(TEST_USERNAME, usernameArgCaptor.getValue()); }
@Test public void testGetCredentialsInvokesGetDecryptedPassphraseValueWithCorrectValuesForLocalAuth() { credentialsHelper.getCredentials(TEST_USERNAME, CredentialsHelper.CREDENTIALS_TYPE.LOCAL_AUTH); ArgumentCaptor<String> usernameArgCaptor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> keyArgCaptor = ArgumentCaptor.forClass(String.class); Mockito.verify(userService, Mockito.times(1)).getDecryptedAccountValue(usernameArgCaptor.capture(), keyArgCaptor.capture()); Assert.assertEquals(TEST_USERNAME, usernameArgCaptor.getValue()); Assert.assertEquals(AccountHelper.INTENT_KEY.ACCOUNT_LOCAL_PASSWORD, keyArgCaptor.getValue()); } |
### Question:
AllCommonsRepository { public List<CommonPersonObject> all() { return personRepository.allcommon(); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void testAll() { allCommonsRepository.all(); verify(personRepository).allcommon(); } |
### Question:
AllCommonsRepository { public CommonPersonObject findByCaseID(String caseId) { return personRepository.findByCaseID(caseId); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void testFindByCaseId() { allCommonsRepository.findByCaseID("case 1"); verify(personRepository).findByCaseID("case 1"); } |
### Question:
AllCommonsRepository { public CommonPersonObject findHHByGOBHHID(String gobhhid) { return personRepository.findHHByGOBHHID(gobhhid); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void testFindHHByGOBHHID() { allCommonsRepository.findHHByGOBHHID("gobhhid 1"); verify(personRepository).findHHByGOBHHID("gobhhid 1"); } |
### Question:
AllCommonsRepository { public List<CommonPersonObject> findByCaseIDs(List<String> caseIds) { return personRepository.findByCaseIDs(caseIds.toArray(new String[caseIds.size()])); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void testFindByCaseIds() { List<String> expectedCaseIds = new ArrayList<>(); expectedCaseIds.add("case 1"); expectedCaseIds.add("case 2"); allCommonsRepository.findByCaseIDs(expectedCaseIds); verify(personRepository).findByCaseIDs(new String[] {expectedCaseIds.get(0), expectedCaseIds.get(1)}); } |
### Question:
AllCommonsRepository { public List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID) { return personRepository .findByRelationalIDs(RelationalID.toArray(new String[RelationalID.size()])); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void testFindByRelationIds() { List<String> expectedRelationIds = new ArrayList<>(); expectedRelationIds.add("relation id 1"); expectedRelationIds.add("relation id 2"); allCommonsRepository.findByRelationalIDs(expectedRelationIds); verify(personRepository).findByRelationalIDs(new String[] {expectedRelationIds.get(0), expectedRelationIds.get(1)}); } |
### Question:
AllCommonsRepository { public List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID) { return personRepository .findByRelational_IDs(RelationalID.toArray(new String[RelationalID.size()])); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void testFindByRelationIds2() { List<String> expectedRelationIds = new ArrayList<>(); expectedRelationIds.add("relation id 1"); expectedRelationIds.add("relation id 2"); allCommonsRepository.findByRelational_IDs(expectedRelationIds); verify(personRepository).findByRelational_IDs(new String[] {expectedRelationIds.get(0), expectedRelationIds.get(1)}); } |
### Question:
AllCommonsRepository { public void close(String entityId) { alertRepository.deleteAllAlertsForEntity(entityId); timelineEventRepository.deleteAllTimelineEventsForEntity(entityId); personRepository.close(entityId); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void testClose() { String entityId = "Entity 1"; allCommonsRepository.close(entityId); verify(alertRepository).deleteAllAlertsForEntity(entityId); verify(timelineEventRepository).deleteAllTimelineEventsForEntity(entityId); verify(personRepository).close(entityId); } |
### Question:
AllCommonsRepository { public void mergeDetails(String entityId, Map<String, String> details) { personRepository.mergeDetails(entityId, details); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void testMergeDetails() { String entityId = "Entity 1"; Map<String, String> details = new HashMap<>(); details.put("case id", "Case 1"); allCommonsRepository.mergeDetails(entityId, details); verify(personRepository).mergeDetails(entityId, details); } |
### Question:
AllCommonsRepository { public void update(String tableName, ContentValues contentValues, String caseId) { personRepository.updateColumn(tableName, contentValues, caseId); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void testUpdate() { String tableName = "sprayed_structures"; String caseId = "Case 1"; ContentValues contentValues = new ContentValues(); contentValues.put("status", "Ready"); allCommonsRepository.update(tableName, contentValues, caseId); verify(personRepository).updateColumn(tableName,contentValues,caseId); } |
### Question:
AllCommonsRepository { public List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName) { return personRepository.customQuery(sql, selections, tableName); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void testCustomQuery() { String tableName = "sprayed_structures"; String sql = "SELECT count(*) FROM sprayed_structures WHERE status = ?"; String[] selectionArgs = {"Complete"}; allCommonsRepository.customQuery(sql, selectionArgs, tableName); verify(personRepository).customQuery(sql, selectionArgs, tableName); } |
### Question:
AllCommonsRepository { public List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections, String tableName) { return personRepository.customQueryForCompleteRow(sql, selections, tableName); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void testCustomQueryForCompleteRow() { String tableName = "sprayed_structures"; String sql = "SELECT count(*) FROM sprayed_structures WHERE status = ?"; String[] selectionArgs = {"Complete"}; allCommonsRepository.customQueryForCompleteRow(sql, selectionArgs, tableName); verify(personRepository).customQueryForCompleteRow(sql, selectionArgs, tableName); } |
### Question:
AllCommonsRepository { public boolean deleteSearchRecord(String caseId) { if (StringUtils.isBlank(caseId)) { return false; } return personRepository.deleteSearchRecord(caseId); } AllCommonsRepository(CommonRepository personRepository, AlertRepository
alertRepository, TimelineEventRepository timelineEventRepository); List<CommonPersonObject> all(); CommonPersonObject findByCaseID(String caseId); CommonPersonObject findHHByGOBHHID(String gobhhid); long count(); List<CommonPersonObject> findByCaseIDs(List<String> caseIds); List<CommonPersonObject> findByRelationalIDs(List<String> RelationalID); List<CommonPersonObject> findByRelational_IDs(List<String> RelationalID); void close(String entityId); void mergeDetails(String entityId, Map<String, String> details); void update(String tableName, ContentValues contentValues, String caseId); List<CommonPersonObject> customQuery(String sql, String[] selections, String tableName); List<CommonPersonObject> customQueryForCompleteRow(String sql, String[] selections,
String tableName); List<String> updateSearch(List<String> caseIds); boolean updateSearch(String caseId); boolean updateSearch(String caseId, String field, String value, String[] listToRemove); boolean deleteSearchRecord(String caseId); }### Answer:
@Test public void testDeleteSearchRecord() { String caseId = "Case id 1"; allCommonsRepository.deleteSearchRecord(caseId); verify(personRepository).deleteSearchRecord(caseId); } |
### Question:
CommonFtsObject { public static String searchTableName(String table) { return table + "_search"; } CommonFtsObject(String[] tables); static String searchTableName(String table); void updateSearchFields(String table, String[] searchFields); void updateSortFields(String table, String[] sortFields); void updateMainConditions(String table, String[] mainConditions); void updateCustomRelationalId(String table, String customRelationalId); void updateAlertScheduleMap(Map<String, Pair<String, Boolean>> alertsScheduleMap); void updateAlertFilterVisitCodes(String[] alertFilterVisitCodes); String[] getTables(); String[] getSearchFields(String table); String[] getSortFields(String table); String[] getMainConditions(String table); String getCustomRelationalId(String table); String getAlertBindType(String schedule); Boolean alertUpdateVisitCode(String schedule); String getAlertScheduleName(String vaccineName); String[] getAlertFilterVisitCodes(); boolean containsTable(String table); static final String idColumn; static final String relationalIdColumn; static final String phraseColumn; static final String isClosedColumn; static final String isClosedColumnName; }### Answer:
@Test public void testSearchTableNameShouldReturnCorrectSearchTableName() { assertEquals("table1_search", commonFtsObject.searchTableName("table1")); } |
### Question:
CommonFtsObject { public boolean containsTable(String table) { if (tables == null || StringUtils.isBlank(table)) { return false; } List<String> tableList = Arrays.asList(tables); return tableList.contains(table); } CommonFtsObject(String[] tables); static String searchTableName(String table); void updateSearchFields(String table, String[] searchFields); void updateSortFields(String table, String[] sortFields); void updateMainConditions(String table, String[] mainConditions); void updateCustomRelationalId(String table, String customRelationalId); void updateAlertScheduleMap(Map<String, Pair<String, Boolean>> alertsScheduleMap); void updateAlertFilterVisitCodes(String[] alertFilterVisitCodes); String[] getTables(); String[] getSearchFields(String table); String[] getSortFields(String table); String[] getMainConditions(String table); String getCustomRelationalId(String table); String getAlertBindType(String schedule); Boolean alertUpdateVisitCode(String schedule); String getAlertScheduleName(String vaccineName); String[] getAlertFilterVisitCodes(); boolean containsTable(String table); static final String idColumn; static final String relationalIdColumn; static final String phraseColumn; static final String isClosedColumn; static final String isClosedColumnName; }### Answer:
@Test public void testContainsTableShouldReturnCorrectStatus() { assertTrue(commonFtsObject.containsTable("table1")); assertFalse(commonFtsObject.containsTable("table100")); } |
### Question:
CommonFtsObject { public String[] getTables() { if (tables == null) { tables = ArrayUtils.EMPTY_STRING_ARRAY; } return tables; } CommonFtsObject(String[] tables); static String searchTableName(String table); void updateSearchFields(String table, String[] searchFields); void updateSortFields(String table, String[] sortFields); void updateMainConditions(String table, String[] mainConditions); void updateCustomRelationalId(String table, String customRelationalId); void updateAlertScheduleMap(Map<String, Pair<String, Boolean>> alertsScheduleMap); void updateAlertFilterVisitCodes(String[] alertFilterVisitCodes); String[] getTables(); String[] getSearchFields(String table); String[] getSortFields(String table); String[] getMainConditions(String table); String getCustomRelationalId(String table); String getAlertBindType(String schedule); Boolean alertUpdateVisitCode(String schedule); String getAlertScheduleName(String vaccineName); String[] getAlertFilterVisitCodes(); boolean containsTable(String table); static final String idColumn; static final String relationalIdColumn; static final String phraseColumn; static final String isClosedColumn; static final String isClosedColumnName; }### Answer:
@Test public void testGetTablesShouldGetAllTables() { assertEquals(tables, commonFtsObject.getTables()); } |
### Question:
CommonObjectFilterOption implements FilterOption { @Override public boolean filter(SmartRegisterClient client) { switch (byColumnAndByDetails) { case byColumn: return ((CommonPersonObjectClient) client).getColumnmaps().get(fieldname). contains(criteria); case byDetails: return (((CommonPersonObjectClient) client).getDetails().get(fieldname) != null ? ((CommonPersonObjectClient) client).getDetails().get(fieldname) : ""). toLowerCase().contains(criteria.toLowerCase()); } return false; } CommonObjectFilterOption(String criteriaArg, String fieldnameArg, ByColumnAndByDetails
byColumnAndByDetailsArg, String filteroptionnameArg); @Override String name(); @Override boolean filter(SmartRegisterClient client); final String fieldname; }### Answer:
@Test public void testFilterByColumn() { Map<String, String> column1 = EasyMap.create("name", "Woman A").map(); CommonPersonObjectClient expectedClient = new CommonPersonObjectClient("entity id 1", emptyMap, "Woman A"); expectedClient.setColumnmaps(column1); boolean filter = commonObjectFilterOption.filter(expectedClient); assertTrue(filter); }
@Test public void testFilterByDetails() { commonObjectFilterOption = new CommonObjectFilterOption(criteria, fieldname, byDetails, filterOptionName); Map<String, String> detail = EasyMap.create("name", "Woman A").map(); CommonPersonObjectClient expectedClient = new CommonPersonObjectClient("entity id 1", detail, "Woman A"); expectedClient.setColumnmaps(emptyMap); boolean filter = commonObjectFilterOption.filter(expectedClient); assertTrue(filter); } |
### Question:
CredentialsHelper { public PasswordHash generateLocalAuthCredentials(char[] password) throws InvalidKeySpecException, NoSuchAlgorithmException { if (password == null) return null; return SecurityHelper.getPasswordHash(password); } CredentialsHelper(Context context); static boolean shouldMigrate(); byte[] getCredentials(String username, String type); void saveCredentials(String type, String encryptedPassphrase); PasswordHash generateLocalAuthCredentials(char[] password); byte[] generateDBCredentials(char[] password, LoginResponseData userInfo); }### Answer:
@Test public void generateLocalAuthCredentials() throws Exception { Assert.assertNotNull(credentialsHelper); PowerMockito.mockStatic(SecurityHelper.class); PowerMockito.when(SecurityHelper.getPasswordHash(TEST_DUMMY_PASSWORD)).thenReturn(null); credentialsHelper.generateLocalAuthCredentials(TEST_DUMMY_PASSWORD); PowerMockito.verifyStatic(SecurityHelper.class); SecurityHelper.getPasswordHash(TEST_DUMMY_PASSWORD); } |
### Question:
CommonObjectFilterOption implements FilterOption { @Override public String name() { return filterOptionName; } CommonObjectFilterOption(String criteriaArg, String fieldnameArg, ByColumnAndByDetails
byColumnAndByDetailsArg, String filteroptionnameArg); @Override String name(); @Override boolean filter(SmartRegisterClient client); final String fieldname; }### Answer:
@Test public void testFilterOptionName() { assertEquals(filterOptionName, commonObjectFilterOption.name()); } |
### Question:
AccountHelper { public static Account getOauthAccountByNameAndType(String accountName, String accountType) { Account[] accounts = accountManager.getAccountsByType(accountType); return accounts.length > 0 ? selectAccount(accounts, accountName) : null; } static Account getOauthAccountByNameAndType(String accountName, String accountType); static Account selectAccount(Account[] accounts, String accountName); static String getAccountManagerValue(String key, String accountName, String accountType); static String getOAuthToken(String accountName, String accountType, String authTokenType); static void invalidateAuthToken(String accountType, String authToken); static String getCachedOAuthToken(String accountName, String accountType, String authTokenType); static AccountManagerFuture<Bundle> reAuthenticateUserAfterSessionExpired(String accountName, String accountType, String authTokenType); final static int MAX_AUTH_RETRIES; }### Answer:
@Test public void testGetOauthAccountByType() { Account account = AccountHelper.getOauthAccountByNameAndType(CORE_ACCOUNT_NAME, CORE_ACCOUNT_TYPE); Assert.assertNotNull(account); Assert.assertEquals(CORE_ACCOUNT_NAME, account.name); } |
### Question:
AccountHelper { public static String getAccountManagerValue(String key, String accountName, String accountType) { Account account = AccountHelper.getOauthAccountByNameAndType(accountName, accountType); if (account != null) { return accountManager.getUserData(account, key); } return null; } static Account getOauthAccountByNameAndType(String accountName, String accountType); static Account selectAccount(Account[] accounts, String accountName); static String getAccountManagerValue(String key, String accountName, String accountType); static String getOAuthToken(String accountName, String accountType, String authTokenType); static void invalidateAuthToken(String accountType, String authToken); static String getCachedOAuthToken(String accountName, String accountType, String authTokenType); static AccountManagerFuture<Bundle> reAuthenticateUserAfterSessionExpired(String accountName, String accountType, String authTokenType); final static int MAX_AUTH_RETRIES; }### Answer:
@Test public void testGetAccountManagerValue() { Whitebox.setInternalState(AccountHelper.class, "accountManager", accountManager); Mockito.doReturn(TEST_VALUE).when(accountManager).getUserData(ArgumentMatchers.any(Account.class), ArgumentMatchers.eq(TEST_KEY)); String value = AccountHelper.getAccountManagerValue(TEST_KEY, CORE_ACCOUNT_NAME, CORE_ACCOUNT_TYPE); Assert.assertNotNull(value); Assert.assertEquals(TEST_VALUE, value); } |
### Question:
AccountHelper { public static String getOAuthToken(String accountName, String accountType, String authTokenType) { Account account = getOauthAccountByNameAndType(accountName, accountType); try { return accountManager.blockingGetAuthToken(account, authTokenType, true); } catch (Exception ex) { Timber.e(ex, "EXCEPTION: %s", ex.toString()); return null; } } static Account getOauthAccountByNameAndType(String accountName, String accountType); static Account selectAccount(Account[] accounts, String accountName); static String getAccountManagerValue(String key, String accountName, String accountType); static String getOAuthToken(String accountName, String accountType, String authTokenType); static void invalidateAuthToken(String accountType, String authToken); static String getCachedOAuthToken(String accountName, String accountType, String authTokenType); static AccountManagerFuture<Bundle> reAuthenticateUserAfterSessionExpired(String accountName, String accountType, String authTokenType); final static int MAX_AUTH_RETRIES; }### Answer:
@Test public void testGetOAuthToken() throws AuthenticatorException, OperationCanceledException, IOException { Mockito.doReturn(TEST_TOKEN_VALUE).when(accountManager).blockingGetAuthToken(new Account(CORE_ACCOUNT_NAME, CORE_ACCOUNT_TYPE), AUTH_TOKEN_TYPE, true); String myToken = AccountHelper.getOAuthToken(CORE_ACCOUNT_NAME, CORE_ACCOUNT_TYPE, AUTH_TOKEN_TYPE); Assert.assertNotNull(myToken); Assert.assertEquals(TEST_TOKEN_VALUE, myToken); } |
### Question:
AccountHelper { public static void invalidateAuthToken(String accountType, String authToken) { if (authToken != null) accountManager.invalidateAuthToken(accountType, authToken); } static Account getOauthAccountByNameAndType(String accountName, String accountType); static Account selectAccount(Account[] accounts, String accountName); static String getAccountManagerValue(String key, String accountName, String accountType); static String getOAuthToken(String accountName, String accountType, String authTokenType); static void invalidateAuthToken(String accountType, String authToken); static String getCachedOAuthToken(String accountName, String accountType, String authTokenType); static AccountManagerFuture<Bundle> reAuthenticateUserAfterSessionExpired(String accountName, String accountType, String authTokenType); final static int MAX_AUTH_RETRIES; }### Answer:
@Test public void testInvalidateAuthToken() { AccountHelper.invalidateAuthToken(CORE_ACCOUNT_TYPE, TEST_TOKEN_VALUE); Mockito.verify(accountManager).invalidateAuthToken(CORE_ACCOUNT_TYPE, TEST_TOKEN_VALUE); } |
### Question:
AccountHelper { public static String getCachedOAuthToken(String accountName, String accountType, String authTokenType) { Account account = getOauthAccountByNameAndType(accountName, accountType); return account != null ? accountManager.peekAuthToken(account, authTokenType) : null; } static Account getOauthAccountByNameAndType(String accountName, String accountType); static Account selectAccount(Account[] accounts, String accountName); static String getAccountManagerValue(String key, String accountName, String accountType); static String getOAuthToken(String accountName, String accountType, String authTokenType); static void invalidateAuthToken(String accountType, String authToken); static String getCachedOAuthToken(String accountName, String accountType, String authTokenType); static AccountManagerFuture<Bundle> reAuthenticateUserAfterSessionExpired(String accountName, String accountType, String authTokenType); final static int MAX_AUTH_RETRIES; }### Answer:
@Test public void testGetCachedOAuthToken() { Account account = new Account(CORE_ACCOUNT_NAME, CORE_ACCOUNT_TYPE); Mockito.doReturn(TEST_TOKEN_VALUE).when(accountManager).peekAuthToken(account, AUTH_TOKEN_TYPE); String cachedAuthToken = AccountHelper.getCachedOAuthToken(CORE_ACCOUNT_NAME, CORE_ACCOUNT_TYPE, AUTH_TOKEN_TYPE); Mockito.verify(accountManager).peekAuthToken(account, AUTH_TOKEN_TYPE); Assert.assertEquals(TEST_TOKEN_VALUE, cachedAuthToken); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.