method2testcases
stringlengths
118
3.08k
### Question: AccountHelper { public static AccountManagerFuture<Bundle> reAuthenticateUserAfterSessionExpired(String accountName, String accountType, String authTokenType) { Account account = getOauthAccountByNameAndType(accountName, accountType); return accountManager.updateCredentials(account, authTokenType, null, null, null, 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 testReAuthenticateUserAfterSessionExpired() { Account account = new Account(CORE_ACCOUNT_NAME, CORE_ACCOUNT_TYPE); Mockito.doReturn(Mockito.mock(AccountManagerFuture.class)).when(accountManager).updateCredentials(account, AUTH_TOKEN_TYPE, null, null, null, null); AccountManagerFuture<Bundle> reAuthenticationFuture = AccountHelper.reAuthenticateUserAfterSessionExpired(CORE_ACCOUNT_NAME, CORE_ACCOUNT_TYPE, AUTH_TOKEN_TYPE); Assert.assertNotNull(reAuthenticationFuture); Mockito.verify(accountManager).updateCredentials(account, AUTH_TOKEN_TYPE, null, null, null, null); }
### Question: RecyclerViewPaginatedAdapter extends RecyclerViewCursorAdapter { @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == RecyclerViewCursorAdapter.Type.FOOTER.ordinal()) { return listItemProvider.createFooterHolder(parent); } else { return listItemProvider.createViewHolder(parent); } } RecyclerViewPaginatedAdapter(Cursor cursor, RecyclerViewProvider<RecyclerView.ViewHolder> listItemProvider, CommonRepository commonRepository); @NonNull @Override RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType); @Override void onBindViewHolder(RecyclerView.ViewHolder viewHolder, Cursor cursor); boolean hasNextPage(); boolean hasPreviousPage(); void nextPageOffset(); void previousPageOffset(); void setTotalcount(int totalcount); int getTotalcount(); void setCurrentoffset(int currentoffset); int getCurrentoffset(); void setCurrentlimit(int currentlimit); int getCurrentlimit(); public int totalcount; public int currentlimit; public int currentoffset; }### Answer: @Test public void testOnCreateViewHolder() { LinearLayout vg = new LinearLayout(context); when(listItemProvider.createViewHolder(any())).thenReturn(mockViewHolder); RecyclerView.ViewHolder actualViewHolder = adapter.onCreateViewHolder(vg, RecyclerViewCursorAdapter.Type.ITEM.ordinal()); assertNotNull(actualViewHolder); verify(listItemProvider).createViewHolder(any()); } @Test public void testOnCreateFooterHolder() { LinearLayout vg = new LinearLayout(context); when(listItemProvider.createFooterHolder(any())).thenReturn(mockViewHolder); RecyclerView.ViewHolder actualViewHolder = adapter.onCreateViewHolder(vg, RecyclerViewCursorAdapter.Type.FOOTER.ordinal()); assertNotNull(actualViewHolder); verify(listItemProvider).createFooterHolder(any()); }
### Question: EligibleCoupleService { public void register(FormSubmission submission) { if (isNotBlank(submission.getFieldValue(AllConstants.CommonFormFields.SUBMISSION_DATE))) { allTimelineEvents.add(TimelineEvent.forECRegistered(submission.entityId(), submission.getFieldValue(AllConstants.CommonFormFields.SUBMISSION_DATE))); } } EligibleCoupleService(AllEligibleCouples allEligibleCouples, AllTimelineEvents allTimelineEvents, AllBeneficiaries allBeneficiaries); void register(FormSubmission submission); void fpComplications(FormSubmission submission); void fpChange(FormSubmission submission); void renewFPProduct(FormSubmission submission); void closeEligibleCouple(FormSubmission submission); }### Answer: @Test public void shouldCreateTimelineEventWhenECIsRegistered() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("entity id 1"); Mockito.when(submission.getFieldValue("submissionDate")).thenReturn("2012-01-01"); service.register(submission); Mockito.verify(allTimelineEvents).add(TimelineEvent.forECRegistered("entity id 1", "2012-01-01")); } @Test public void shouldNotCreateTimelineEventWhenECIsRegisteredWithoutSubmissionDate() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("entity id 1"); Mockito.when(submission.getFieldValue("submissionDate")).thenReturn(null); service.register(submission); Mockito.verifyZeroInteractions(allTimelineEvents); }
### Question: EligibleCoupleService { public void closeEligibleCouple(FormSubmission submission) { allEligibleCouples.close(submission.entityId()); allBeneficiaries.closeAllMothersForEC(submission.entityId()); } EligibleCoupleService(AllEligibleCouples allEligibleCouples, AllTimelineEvents allTimelineEvents, AllBeneficiaries allBeneficiaries); void register(FormSubmission submission); void fpComplications(FormSubmission submission); void fpChange(FormSubmission submission); void renewFPProduct(FormSubmission submission); void closeEligibleCouple(FormSubmission submission); }### Answer: @Test public void shouldCloseEC() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("entity id 1"); service.closeEligibleCouple(submission); Mockito.verify(allEligibleCouples).close("entity id 1"); Mockito.verify(allBeneficiaries).closeAllMothersForEC("entity id 1"); }
### Question: DocumentConfigurationService { @VisibleForTesting protected void saveManifestVersion(@NonNull String manifestVersion) { boolean manifestVersionSaved = CoreLibrary.getInstance() .context() .allSharedPreferences() .saveManifestVersion(manifestVersion); if (!manifestVersionSaved) { Timber.e(new Exception("Saving manifest version failed")); } } DocumentConfigurationService(HTTPAgent httpAgentArg, ManifestRepository manifestRepositoryArg, ClientFormRepository clientFormRepositoryArg, DristhiConfiguration configurationArg); void fetchManifest(); static final String MANIFEST_FORMS_VERSION; static final String FORM_VERSION; static final String CURRENT_FORM_VERSION; static final String IDENTIFIERS; }### Answer: @Test public void saveManifestVersionShouldSaveVersionInSharedPreferences() { Assert.assertNull(CoreLibrary.getInstance().context().allSharedPreferences().fetchManifestVersion()); String manifestVersion = "0.0.89"; documentConfigurationService.saveManifestVersion(manifestVersion); Assert.assertEquals(manifestVersion, CoreLibrary.getInstance().context().allSharedPreferences().fetchManifestVersion()); }
### Question: AppProperties extends Properties { public Boolean getPropertyBoolean(String key) { return Boolean.valueOf(getProperty(key)); } Boolean getPropertyBoolean(String key); Boolean hasProperty(String key); Boolean isTrue(String key); }### Answer: @Test public void testGetPropertyBooleanReturnsCorrectValue() { AppProperties properties = new AppProperties(); Boolean value = properties.getPropertyBoolean(PROP_KEY); Assert.assertNotNull(value); Assert.assertFalse(value); properties.setProperty(PROP_KEY, TEST_VAL_TRUE); value = properties.getPropertyBoolean(PROP_KEY); Assert.assertNotNull(value); Assert.assertTrue(value); }
### Question: AppProperties extends Properties { public Boolean hasProperty(String key) { return getProperty(key) != null; } Boolean getPropertyBoolean(String key); Boolean hasProperty(String key); Boolean isTrue(String key); }### Answer: @Test public void testHasPropertyReturnsCorrectValue() { AppProperties properties = new AppProperties(); Boolean value = properties.hasProperty(PROP_KEY); Assert.assertNotNull(value); Assert.assertFalse(value); properties.setProperty(PROP_KEY, TEST_VAL); value = properties.hasProperty(PROP_KEY); Assert.assertNotNull(value); Assert.assertTrue(value); }
### Question: FloatUtil { public static Float tryParse(String value, Float defaultValue) { try { return Float.parseFloat(value); } catch (NumberFormatException e) { return defaultValue; } } static Float tryParse(String value, Float defaultValue); static String tryParse(String value, String defaultValue); }### Answer: @Test public void assertTryParseWithInvalidValue() { Assert.assertEquals(FloatUtil.tryParse("invalid", 1.0f), 1.0f); Assert.assertEquals(FloatUtil.tryParse("invalid", "1"), "1"); } @Test public void assertTryParseWithValidValue() { Assert.assertEquals(FloatUtil.tryParse("1", 1.0f), 1.0f); Assert.assertEquals(FloatUtil.tryParse("1", "1"), "1.0"); }
### Question: StringUtil { public static String humanize(String value) { return capitalize(replace(getValue(value), "_", " ")); } static String humanize(String value); static String replaceAndHumanize(String value, String oldCharacter, String newCharacter); static String replaceAndHumanizeWithInitCapText(String value, String oldCharacter, String newCharacter); static String humanizeAndDoUPPERCASE(String value); static String humanizeAndUppercase(String value, String... skipTokens); static String getValue(String value); }### Answer: @Test public void assertShouldCapitalize() throws Exception { org.junit.Assert.assertEquals("Abc", org.smartregister.util.StringUtil.humanize("abc")); org.junit.Assert.assertEquals("Abc", org.smartregister.util.StringUtil.humanize("Abc")); } @Test public void shouldReplaceUnderscoreWithSpace() throws Exception { org.junit.Assert.assertEquals("Abc def", org.smartregister.util.StringUtil.humanize("abc_def")); org.junit.Assert.assertEquals("Abc def", org.smartregister.util.StringUtil.humanize("Abc_def")); } @Test public void assertShouldHandleEmptyAndNull() throws Exception { org.junit.Assert.assertEquals("", org.smartregister.util.StringUtil.humanize("")); }
### Question: HTTPAgent { public Response<String> postWithJsonResponse(String postURLPath, String jsonPayload) { logResponse(postURLPath, jsonPayload); return post(postURLPath, jsonPayload); } HTTPAgent(Context context, AllSharedPreferences allSharedPreferences, DristhiConfiguration configuration); Response<String> fetch(String requestURLPath); void invalidateExpiredCachedAccessToken(); Response<String> post(String postURLPath, String jsonPayload); Response<String> postWithJsonResponse(String postURLPath, String jsonPayload); LoginResponse urlCanBeAccessWithGivenCredentials(String requestURL, String userName, char[] password); DownloadStatus downloadFromUrl(String url, String filename); Response<String> fetchWithCredentials(String requestURL, String accessToken); String httpImagePost(String urlString, ProfileImage image); int getReadTimeout(); int getConnectTimeout(); void setConnectTimeout(int connectTimeout); void setReadTimeout(int readTimeout); AccountResponse oauth2authenticateCore(StringBuffer requestParamBuffer, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticate(String username, char[] password, String grantType, String tokenEndpointURL); AccountResponse oauth2authenticateRefreshToken(String refreshToken); LoginResponse fetchUserDetails(String requestURL, String oauthAccessToken); Response<DownloadStatus> downloadFromURL(String downloadURL_, String fileName); boolean verifyAuthorization(); boolean verifyAuthorizationLegacy(); AccountConfiguration fetchOAuthConfiguration(); static final int FILE_UPLOAD_CHUNK_SIZE_BYTES; }### Answer: @Test public void testPostWithJsonResponse() { PowerMockito.mockStatic(Base64.class); HashMap<String, String> map = new HashMap<>(); map.put("title", "OpenSRP Testing Tuesdays"); JSONObject jObject = new JSONObject(map); Response<String> resp = httpAgent.postWithJsonResponse("http: Assert.assertEquals(ResponseStatus.success, resp.status()); }
### Question: StringUtil { public static String replaceAndHumanize(String value, String oldCharacter, String newCharacter) { return humanize(replace(getValue(value), oldCharacter, newCharacter)); } static String humanize(String value); static String replaceAndHumanize(String value, String oldCharacter, String newCharacter); static String replaceAndHumanizeWithInitCapText(String value, String oldCharacter, String newCharacter); static String humanizeAndDoUPPERCASE(String value); static String humanizeAndUppercase(String value, String... skipTokens); static String getValue(String value); }### Answer: @Test public void assertReplaceAndHumanizeCallsHumanize() throws Exception { org.junit.Assert.assertEquals("Abc def", StringUtil.replaceAndHumanize("abc def", " ", "_")); }
### Question: AlertService { public void deleteAll(Action action) { repository.deleteAllAlertsForEntity(action.caseID()); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String, AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String value); }### Answer: @Test public void shouldDeleteAllFromRepositoryForDeleteAllActions() throws Exception { Action firstAction = ActionBuilder.actionForDeleteAllAlert("Case X"); Action secondAction = ActionBuilder.actionForDeleteAllAlert("Case Y"); service.deleteAll(firstAction); service.deleteAll(secondAction); Mockito.verify(alertRepository).deleteAllAlertsForEntity("Case X"); Mockito.verify(alertRepository).deleteAllAlertsForEntity("Case Y"); Mockito.verifyNoMoreInteractions(alertRepository); }
### Question: AlertService { public List<Alert> findByEntityId(String entityId) { return repository.findByEntityId(entityId); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String, AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String value); }### Answer: @Test public void testFindEntityById() { service.findByEntityId("entity-id"); Mockito.verify(alertRepository).findByEntityId("entity-id"); }
### Question: StringUtil { public static String replaceAndHumanizeWithInitCapText(String value, String oldCharacter, String newCharacter) { return humanize(WordUtils.capitalize(replace(getValue(value), oldCharacter, newCharacter))); } static String humanize(String value); static String replaceAndHumanize(String value, String oldCharacter, String newCharacter); static String replaceAndHumanizeWithInitCapText(String value, String oldCharacter, String newCharacter); static String humanizeAndDoUPPERCASE(String value); static String humanizeAndUppercase(String value, String... skipTokens); static String getValue(String value); }### Answer: @Test public void assertReplaceAndHumanizeWithInitCapTextCallsHumanize() throws Exception { org.junit.Assert.assertEquals("Abc def", StringUtil.replaceAndHumanizeWithInitCapText("abc def", " ", "_")); }
### Question: AlertService { public List<Alert> findByEntityIdAndAlertNames(String entityId, String... names) { return repository.findByEntityIdAndAlertNames(entityId, names); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String, AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String value); }### Answer: @Test public void testFindByEntityIdAndAlertNames() { service.findByEntityIdAndAlertNames("Entity 1", "AncAlert"); Mockito.verify(alertRepository).findByEntityIdAndAlertNames("Entity 1", "AncAlert"); }
### Question: AlertService { public List<Alert> findByEntityIdAndOffline(String entityId, String... names) { return repository.findOfflineByEntityIdAndName(entityId, names); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String, AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String value); }### Answer: @Test public void testByEntityIdAndOffline() { service.findByEntityIdAndOffline("Entity 1", "PncAlert"); Mockito.verify(alertRepository).findOfflineByEntityIdAndName("Entity 1", "PncAlert"); }
### Question: AlertService { public Alert findByEntityIdAndScheduleName(String entityId, String scheduleName) { return repository.findByEntityIdAndScheduleName(entityId, scheduleName); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String, AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String value); }### Answer: @Test public void testFindByEntityIdAndScheduleName() { service.findByEntityIdAndScheduleName("Entity 1", "Schedule 1"); Mockito.verify(alertRepository).findByEntityIdAndScheduleName("Entity 1", "Schedule 1"); }
### Question: AlertService { public void changeAlertStatusToInProcess(String entityId, String alertName) { repository.changeAlertStatusToInProcess(entityId, alertName); updateFtsSearchAfterStatusChange(entityId, alertName); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String, AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String value); }### Answer: @Test public void testChangeAlertStatusToInProcess() { service = spy(service); service.changeAlertStatusToInProcess("Entity 1", "AncAlert"); Mockito.verify(alertRepository).changeAlertStatusToInProcess("Entity 1", "AncAlert"); Mockito.verify(service).updateFtsSearchAfterStatusChange("Entity 1", "AncAlert"); }
### Question: AlertService { public void changeAlertStatusToComplete(String entityId, String alertName) { repository.changeAlertStatusToComplete(entityId, alertName); updateFtsSearchAfterStatusChange(entityId, alertName); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String, AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String value); }### Answer: @Test public void testChangeAlertStatusToComplete() { service = spy(service); service.changeAlertStatusToComplete("Entity 1", "AncAlert"); Mockito.verify(alertRepository).changeAlertStatusToComplete("Entity 1", "AncAlert"); Mockito.verify(service).updateFtsSearchAfterStatusChange("Entity 1", "AncAlert"); }
### Question: AlertService { public void deleteAlert(String entityId, String visitCode) { repository.deleteVaccineAlertForEntity(entityId, visitCode); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String, AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String value); }### Answer: @Test public void testDeleteAlert() { service.deleteAlert("Entity 1", "Visit 1"); Mockito.verify(alertRepository).deleteVaccineAlertForEntity("Entity 1", "Visit 1"); }
### Question: AlertService { public void deleteOfflineAlerts(String entityId) { repository.deleteOfflineAlertsForEntity(entityId); } AlertService(AlertRepository repository); AlertService(AlertRepository repository, CommonFtsObject commonFtsObject, Map<String, AllCommonsRepository> allCommonsRepositoryMap); void create(Action action); void create(Alert alert); void close(Action action); void deleteAll(Action action); List<Alert> findByEntityId(String entityId); List<Alert> findByEntityIdAndAlertNames(String entityId, String... names); List<Alert> findByEntityIdAndOffline(String entityId, String... names); Alert findByEntityIdAndScheduleName(String entityId, String scheduleName); void changeAlertStatusToInProcess(String entityId, String alertName); void changeAlertStatusToComplete(String entityId, String alertName); void deleteAlert(String entityId, String visitCode); void deleteOfflineAlerts(String entityId); void deleteOfflineAlerts(String entityId, String... names); void updateFtsSearchAfterStatusChange(String entityId, String alertName); void updateFtsSearch(Alert alert, boolean statusChange); boolean updateFtsSearchInACR(String bindType, String entityId, String field, String value); }### Answer: @Test public void testDeleteOfflineAlerts() { service.deleteOfflineAlerts("Entity 1"); Mockito.verify(alertRepository).deleteOfflineAlertsForEntity("Entity 1"); } @Test public void testDeleteOfflineAlertsWithNames() { service.deleteOfflineAlerts("Entity 1", "AncAlert"); Mockito.verify(alertRepository).deleteOfflineAlertsForEntity("Entity 1", "AncAlert"); }
### Question: StringUtil { public static String humanizeAndUppercase(String value, String... skipTokens) { String res = humanizeAndDoUPPERCASE(value); for (String s : skipTokens) { res = res.replaceAll("(?i)" + s, s); } return res; } static String humanize(String value); static String replaceAndHumanize(String value, String oldCharacter, String newCharacter); static String replaceAndHumanizeWithInitCapText(String value, String oldCharacter, String newCharacter); static String humanizeAndDoUPPERCASE(String value); static String humanizeAndUppercase(String value, String... skipTokens); static String getValue(String value); }### Answer: @Test public void assertHumanizeAndUppercase() throws Exception { org.junit.Assert.assertEquals("ABC DEF", StringUtil.humanizeAndUppercase("abc def", " ")); }
### Question: ChildService { public void close(FormSubmission submission) { allBeneficiaries.closeChild(submission.entityId()); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); }### Answer: @Test public void shouldCloseChildRecordForDeleteChildAction() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("child id 1"); service.close(submission); Mockito.verify(allBeneficiaries).closeChild("child id 1"); }
### Question: ChildService { public void updateVitaminAProvided(FormSubmission submission) { serviceProvidedService.add(ServiceProvided.forVitaminAProvided(submission.entityId(), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DATE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_DOSE), submission.getFieldValue(AllConstants.VitaminAFields.VITAMIN_A_PLACE))); } ChildService(AllBeneficiaries allBeneficiariesArg, MotherRepository motherRepositoryArg, ChildRepository childRepositoryArg, AllTimelineEvents allTimelineEventsArg, ServiceProvidedService serviceProvidedServiceArg, AllAlerts allAlertsArg); void register(FormSubmission submission); void registerForEC(FormSubmission submission); void pncRegistrationOA(FormSubmission submission); void updateImmunizations(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void close(FormSubmission submission); void updatePhotoPath(String entityId, String imagePath); void updateIllnessStatus(FormSubmission submission); void updateVitaminAProvided(FormSubmission submission); void registerForOA(FormSubmission submission); }### Answer: @Test public void shouldUpdateVitaminADosagesForUpdateVitaminAProvidedAction() throws Exception { FormSubmission submission = Mockito.mock(FormSubmission.class); Mockito.when(submission.entityId()).thenReturn("child id 1"); Mockito.when(submission.getFieldValue("vitaminADate")).thenReturn("2012-01-01"); Mockito.when(submission.getFieldValue("vitaminADose")).thenReturn("1"); Mockito.when(submission.getFieldValue("vitaminAPlace")).thenReturn("PHC"); service.updateVitaminAProvided(submission); Mockito.verify(serviceProvidedService).add(ServiceProvided.forVitaminAProvided("child id 1", "2012-01-01", "1", "PHC")); }
### Question: ReplicationIntentService extends IntentService { @Override protected void onHandleIntent(Intent intent) { } ReplicationIntentService(String name); ReplicationIntentService(); }### Answer: @Test public void assertReplicationIntentServiceInitializationTest() { ReplicationIntentService replicationIntentService = new ReplicationIntentService(); Assert.assertNotNull(replicationIntentService); replicationIntentService.onHandleIntent(null); } @Test public void assertReplicationIntentServiceInitializationTest2() { ReplicationIntentService replicationIntentService = new ReplicationIntentService("service_name"); Assert.assertNotNull(replicationIntentService); replicationIntentService.onHandleIntent(null); }
### Question: MotherService { public void registerANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; }### Answer: @Test public void shouldRegisterANC() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("motherId")).thenReturn("mother id 1"); when(submission.getFieldValue("thayiCardNumber")).thenReturn("thayi 1"); when(submission.getFieldValue("registrationDate")).thenReturn("2012-01-02"); when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); service.registerANC(submission); allTimelineEvents.add(TimelineEvent.forStartOfPregnancy("mother id 1", "2012-01-02", "2012-01-01")); allTimelineEvents.add(TimelineEvent.forStartOfPregnancyForEC("entity id 1", "thayi 1", "2012-01-02", "2012-01-01")); }
### Question: MotherService { public void registerOutOfAreaANC(FormSubmission submission) { addTimelineEventsForMotherRegistration(submission); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; }### Answer: @Test public void shouldRegisterOutOfAreaANC() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("motherId")).thenReturn("mother id 1"); when(submission.getFieldValue("thayiCardNumber")).thenReturn("thayi 1"); when(submission.getFieldValue("registrationDate")).thenReturn("2012-01-02"); when(submission.getFieldValue("referenceDate")).thenReturn("2012-01-01"); service.registerOutOfAreaANC(submission); allTimelineEvents.add(TimelineEvent.forStartOfPregnancy("mother id 1", "2012-01-02", "2012-01-01")); allTimelineEvents.add(TimelineEvent.forStartOfPregnancyForEC("entity id 1", "thayi 1", "2012-01-02", "2012-01-01")); }
### Question: MotherService { public void ttProvided(FormSubmission submission) { allTimelines.add(forTTShotProvided(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); serviceProvidedService .add(forTTDose(submission.entityId(), submission.getFieldValue(TT_DOSE), submission.getFieldValue(TT_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; }### Answer: @Test public void shouldHandleTTProvided() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("ttDose")).thenReturn("ttbooster"); when(submission.getFieldValue("ttDate")).thenReturn("2013-01-01"); service.ttProvided(submission); verify(allTimelineEvents).add(forTTShotProvided("entity id 1", "ttbooster", "2013-01-01")); verify(serviceProvidedService).add(new ServiceProvided("entity id 1", "TT Booster", "2013-01-01", mapOf("dose", "TT Booster"))); }
### Question: MotherService { public void hbTest(FormSubmission submission) { serviceProvidedService .add(forHBTest(submission.entityId(), submission.getFieldValue(HB_LEVEL), submission.getFieldValue(HB_TEST_DATE))); } MotherService(AllBeneficiaries allBeneficiaries, AllEligibleCouples allEligibleCouples, AllTimelineEvents allTimelineEvents, ServiceProvidedService serviceProvidedService); void registerANC(FormSubmission submission); void registerOutOfAreaANC(FormSubmission submission); void ancVisit(FormSubmission submission); void close(FormSubmission submission); void close(String entityId, String reason); void ttProvided(FormSubmission submission); void ifaTabletsGiven(FormSubmission submission); void hbTest(FormSubmission submission); void deliveryOutcome(FormSubmission submission); void pncVisitHappened(FormSubmission submission); void deliveryPlan(FormSubmission submission); static final String MOTHER_ID; static String submissionDate; }### Answer: @Test public void shouldHandleHBTest() throws Exception { FormSubmission submission = mock(FormSubmission.class); when(submission.entityId()).thenReturn("entity id 1"); when(submission.getFieldValue("hbLevel")).thenReturn("11"); when(submission.getFieldValue("hbTestDate")).thenReturn("2013-01-01"); service.hbTest(submission); verify(serviceProvidedService).add(new ServiceProvided("entity id 1", "Hb Test", "2013-01-01", mapOf("hbLevel", "11"))); }
### Question: SecurityHelper { public static char[] readValue(Editable editable) { char[] chars = new char[editable.length()]; editable.getChars(0, editable.length(), chars, 0); return chars; } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; }### Answer: @Test public void testReadValueClearsEditableAfterReadingValue() { Mockito.doReturn(2).when(editable).length(); SecurityHelper.readValue(editable); ArgumentCaptor<Integer> lengthCaptor = ArgumentCaptor.forClass(Integer.class); ArgumentCaptor<char[]> charsCaptor = ArgumentCaptor.forClass(char[].class); ArgumentCaptor<Integer> firstArgCaptor = ArgumentCaptor.forClass(Integer.class); ArgumentCaptor<Integer> lastArgCaptor = ArgumentCaptor.forClass(Integer.class); Mockito.verify(editable).getChars(firstArgCaptor.capture(), lengthCaptor.capture(), charsCaptor.capture(), lastArgCaptor.capture()); Assert.assertEquals(2, lengthCaptor.getValue().intValue()); Assert.assertEquals(0, firstArgCaptor.getValue().intValue()); Assert.assertEquals(0, lastArgCaptor.getValue().intValue()); }
### Question: SecurityHelper { public static void clearArray(byte[] array) { if (array != null) { Arrays.fill(array, (byte) 0); } } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; }### Answer: @Test public void clearArray() { byte[] sensitiveDataArray = SecurityHelper.toBytes(TEST_PASSWORD); SecurityHelper.clearArray(sensitiveDataArray); Assert.assertNotNull(sensitiveDataArray); for (byte c : sensitiveDataArray) { Assert.assertEquals((byte) 0, c); } } @Test public void testClearArrayOverwritesCharArrayValuesWithAsterisk() { char[] sensitiveDataArray = TEST_PASSWORD; SecurityHelper.clearArray(sensitiveDataArray); Assert.assertNotNull(sensitiveDataArray); for (char c : sensitiveDataArray) { Assert.assertEquals('*', c); } }
### Question: SecurityHelper { public static byte[] toBytes(StringBuffer stringBuffer) throws CharacterCodingException { CharsetEncoder encoder = CHARSET.newEncoder(); CharBuffer buffer = CharBuffer.wrap(stringBuffer); ByteBuffer bytesBuffer = encoder.encode(buffer); byte[] bytes = bytesBuffer.array(); clearArray(bytesBuffer.array()); clearStringBuffer(stringBuffer); return bytes; } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; }### Answer: @Test public void testToBytes() throws CharacterCodingException { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(TEST_PASSWORD); byte[] testPasswordBytes = SecurityHelper.toBytes(stringBuffer); Assert.assertNotNull(testPasswordBytes); Assert.assertEquals(TEST_PASSWORD.length + 1, testPasswordBytes.length); }
### Question: SecurityHelper { public static byte[] nullSafeBase64Decode(String base64EncodedValue) { if (!StringUtils.isBlank(base64EncodedValue)) { return Base64.decode(base64EncodedValue, Base64.DEFAULT); } else { return null; } } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; }### Answer: @Test public void nullSafeBase64DecodeDoesNotThrowExceptionIfParameterIsNull() { PowerMockito.mockStatic(Base64.class); PowerMockito.when(Base64.decode(ArgumentMatchers.anyString(), ArgumentMatchers.eq(Base64.DEFAULT))).thenReturn(new byte[]{0, 1}); byte[] decoded = SecurityHelper.nullSafeBase64Decode(null); Assert.assertNull(decoded); }
### Question: SecurityHelper { public static char[] generateRandomPassphrase() { return RandomStringUtils.randomAlphanumeric(PASSPHRASE_SIZE).toCharArray(); } static char[] readValue(Editable editable); static void clearArray(byte[] array); static void clearArray(char[] array); static byte[] toBytes(StringBuffer stringBuffer); static byte[] toBytes(char[] chars); static char[] toChars(byte[] bytes); static PasswordHash getPasswordHash(char[] password); static byte[] hashPassword(char[] password, byte[] salt); static byte[] nullSafeBase64Decode(String base64EncodedValue); static char[] generateRandomPassphrase(); static final int ITERATION_COUNT; }### Answer: @Test public void testGenerateRandomPassphraseGeneratesAlphanumericArray() { char[] value = SecurityHelper.generateRandomPassphrase(); Assert.assertNotNull(value); Assert.assertTrue(StringUtils.isAlphanumeric(new StringBuilder().append(value).toString())); Assert.assertEquals(32, value.length); }
### Question: CampaignRepository extends BaseRepository { public List<Campaign> getAllCampaigns() { Cursor cursor = null; List<Campaign> campaigns = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null); while (cursor.moveToNext()) { campaigns.add(readCursor(cursor)); } cursor.close(); } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return campaigns; } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); }### Answer: @Test public void tesGetCampaignsAllCampaigns() { when(sqLiteDatabase.rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null)).thenReturn(getCursor()); List<Campaign> allCampaigns = campaignRepository.getAllCampaigns(); verify(sqLiteDatabase).rawQuery("SELECT * FROM " + CAMPAIGN_TABLE, null); assertEquals(1, allCampaigns.size()); assertEquals(campaignJson, gson.toJson(allCampaigns.get(0))); }
### Question: CampaignRepository extends BaseRepository { public Campaign getCampaignByIdentifier(String identifier) { Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + CAMPAIGN_TABLE + " WHERE " + ID + " =?", new String[]{identifier}); if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return null; } static void createTable(SQLiteDatabase database); void addOrUpdate(Campaign campaign); List<Campaign> getAllCampaigns(); Campaign getCampaignByIdentifier(String identifier); }### Answer: @Test public void testGetCampaignByIdentifier() { when(sqLiteDatabase.rawQuery("SELECT * FROM campaign WHERE _id =?", new String[]{"IRS_2018_S1"})).thenReturn(getCursor()); Campaign campaign = campaignRepository.getCampaignByIdentifier("IRS_2018_S1"); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals(1, argsCaptor.getValue().length); assertEquals("IRS_2018_S1", argsCaptor.getValue()[0]); assertEquals("SELECT * FROM campaign WHERE _id =?", stringArgumentCaptor.getValue()); assertEquals(campaignJson, gson.toJson(campaign)); }
### Question: TaskNotesRepository extends BaseRepository { public void addOrUpdate(Note note, String taskId) { if (StringUtils.isBlank(taskId)) { throw new IllegalArgumentException("taskId must be specified"); } ContentValues contentValues = new ContentValues(); contentValues.put(TASK_ID, taskId); contentValues.put(AUTHOR, note.getAuthorString()); contentValues.put(TIME, note.getTime().getMillis()); contentValues.put(TEXT, note.getText()); getWritableDatabase().replace(TASK_NOTES_TABLE, null, contentValues); } static void createTable(SQLiteDatabase database); void addOrUpdate(Note note, String taskId); List<Note> getNotesByTask(String taskId); }### Answer: @Test public void testAddOrUpdateShouldAdd() { Note note = new Note(); note.setText("Should be completed by End of November"); Long now = System.currentTimeMillis(); note.setTime(new DateTime(now)); note.setAuthorString("jdoe"); taskNotesRepository.addOrUpdate(note, "task22132"); verify(sqLiteDatabase).replace(stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), contentValuesArgumentCaptor.capture()); assertEquals(2, stringArgumentCaptor.getAllValues().size()); Iterator<String> iterator = stringArgumentCaptor.getAllValues().iterator(); assertEquals(TASK_NOTES_TABLE, iterator.next()); assertNull(iterator.next()); ContentValues contentValues = contentValuesArgumentCaptor.getValue(); assertEquals(4, contentValues.size()); assertEquals("task22132", contentValues.getAsString("task_id")); assertEquals("Should be completed by End of November", contentValues.getAsString("text")); assertEquals("jdoe", contentValues.getAsString("author")); assertEquals(now, contentValues.getAsLong("time")); }
### Question: TaskNotesRepository extends BaseRepository { public List<Note> getNotesByTask(String taskId) { List<Note> notes = new ArrayList<>(); Cursor cursor = null; try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + TASK_NOTES_TABLE + " WHERE " + TASK_ID + " =?", new String[]{taskId}); while (cursor.moveToNext()) { notes.add(readCursor(cursor)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return notes; } static void createTable(SQLiteDatabase database); void addOrUpdate(Note note, String taskId); List<Note> getNotesByTask(String taskId); }### Answer: @Test public void tesGetTasksAllTasks() { when(sqLiteDatabase.rawQuery("SELECT * FROM task_note WHERE task_id =?", new String[]{"task22132"})).thenReturn(getCursor()); List<Note> notes = taskNotesRepository.getNotesByTask("task22132"); verify(sqLiteDatabase).rawQuery("SELECT * FROM task_note WHERE task_id =?", new String[]{"task22132"}); assertEquals(1, notes.size()); assertEquals("Should be completed by End of November", notes.get(0).getText()); assertEquals("jdoe", notes.get(0).getAuthorString()); assertEquals(1543232476345l, notes.get(0).getTime().getMillis()); }
### Question: FormUtils { public static int getIndexForFormName(String formName, String[] formNames) { for (int i = 0; i < formNames.length; i++) { if (formName.equalsIgnoreCase(formNames[i])) { return i; } } return -1; } FormUtils(Context context); static FormUtils getInstance(Context ctx); static boolean hasChildElements(Node element); static int getIndexForFormName(String formName, String[] formNames); FormSubmission generateFormSubmisionFromXMLString(String entity_id, String formData, String formName, JSONObject overrides); String generateXMLInputForFormWithEntityId(String entityId, String formName, String overrides); Object getObjectAtPath(String[] path, JSONObject jsonObject); JSONArray getPopulatedFieldsForArray(JSONObject fieldsDefinition, String entityId, JSONObject jsonObject, JSONObject overrides); String retrieveValueForLinkedRecord(String link, JSONObject entityJson); JSONArray getFieldsArrayForSubFormDefinition(JSONObject fieldsDefinition); JSONObject getFieldValuesForSubFormDefinition(JSONObject fieldsDefinition, String relationalId, String entityId, JSONObject jsonObject, JSONObject overrides); String getValueForPath(String[] path, JSONObject jsonObject); JSONObject getFormJson(String formIdentity); static final String TAG; static final String ecClientRelationships; }### Answer: @Test public void getIndexForFormNameShouldReturnCorrectIndex() { String[] formNames = new String[] {"Birth Reg", "Immunisation Reg", "Death Form"}; Assert.assertEquals(1, formUtils.getIndexForFormName("Immunisation Reg", formNames)); }
### Question: AllSettings { public void savePreviousFetchIndex(String value) { settingsRepository.updateSetting(PREVIOUS_FETCH_INDEX_SETTING_KEY, value); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void shouldSavePreviousFetchIndex() throws Exception { allSettings.savePreviousFetchIndex("1234"); Mockito.verify(settingsRepository).updateSetting("previousFetchIndex", "1234"); }
### Question: AllSettings { public String fetchPreviousFetchIndex() { return settingsRepository.querySetting(PREVIOUS_FETCH_INDEX_SETTING_KEY, "0"); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void shouldFetchPreviousFetchIndex() throws Exception { Mockito.when(settingsRepository.querySetting("previousFetchIndex", "0")).thenReturn("1234"); String actual = allSettings.fetchPreviousFetchIndex(); Mockito.verify(settingsRepository).querySetting("previousFetchIndex", "0"); Assert.assertEquals("1234", actual); }
### Question: AllSettings { public void savePreviousFormSyncIndex(String value) { settingsRepository.updateSetting(PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY, value); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void shouldSavePreviousFormSyncIndex() throws Exception { allSettings.savePreviousFormSyncIndex("1234"); Mockito.verify(settingsRepository).updateSetting("previousFormSyncIndex", "1234"); }
### Question: AllSettings { public String fetchPreviousFormSyncIndex() { return settingsRepository.querySetting(PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY, "0"); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void shouldFetchPreviousFormSyncIndex() throws Exception { Mockito.when(settingsRepository.querySetting("previousFormSyncIndex", "0")).thenReturn("1234"); String actual = allSettings.fetchPreviousFormSyncIndex(); Mockito.verify(settingsRepository).querySetting("previousFormSyncIndex", "0"); Assert.assertEquals("1234", actual); }
### Question: AllSettings { public void saveAppliedVillageFilter(String village) { settingsRepository.updateSetting(APPLIED_VILLAGE_FILTER_SETTING_KEY, village); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void shouldSaveAppliedVillageFilter() throws Exception { allSettings.saveAppliedVillageFilter("munjanahalli"); Mockito.verify(settingsRepository).updateSetting("appliedVillageFilter", "munjanahalli"); }
### Question: AllSettings { public String appliedVillageFilter(String defaultFilterValue) { return settingsRepository .querySetting(APPLIED_VILLAGE_FILTER_SETTING_KEY, defaultFilterValue); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void shouldGetAppliedVillageFilter() throws Exception { allSettings.appliedVillageFilter("All"); Mockito.verify(settingsRepository).querySetting("appliedVillageFilter", "All"); }
### Question: AllSettings { public void registerANM(String userName) { preferences.updateANMUserName(userName); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void assertRegisterANMCallsPreferenceAndRepositoryUpdate() throws Exception { Mockito.doNothing().when(allSharedPreferences).updateANMUserName(Mockito.anyString()); allSettings.registerANM(""); Mockito.verify(allSharedPreferences, Mockito.times(1)).updateANMUserName(Mockito.anyString()); }
### Question: AllSettings { public void saveANMLocation(String anmLocation) { settingsRepository.updateSetting(ANM_LOCATION, anmLocation); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void assertSaveANMLocationCallsRepositoryUpdate() { Mockito.doNothing().doNothing().when(settingsRepository).updateSetting(Mockito.anyString(), Mockito.anyString()); allSettings.saveANMLocation(""); Mockito.verify(settingsRepository, Mockito.times(1)).updateSetting(Mockito.anyString(), Mockito.anyString()); }
### Question: AllSettings { public String fetchANMLocation() { return settingsRepository.querySetting(ANM_LOCATION, ""); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void assertFetchANMLocationCallsRepositoryQuery() { Mockito.when(settingsRepository.querySetting(Mockito.anyString(), Mockito.anyString())).thenReturn(""); Assert.assertEquals(allSettings.fetchANMLocation(), ""); Mockito.verify(settingsRepository, Mockito.times(1)).querySetting(Mockito.anyString(), Mockito.anyString()); }
### Question: AllSettings { public String fetchUserInformation() { return settingsRepository.querySetting(USER_INFORMATION, ""); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void assertFetchUserInformationCallsRepositoryQuery() { Mockito.when(settingsRepository.querySetting(Mockito.anyString(), Mockito.anyString())).thenReturn(""); Assert.assertEquals(allSettings.fetchUserInformation(), ""); Mockito.verify(settingsRepository, Mockito.times(1)).querySetting(Mockito.anyString(), Mockito.anyString()); }
### Question: AllSettings { public void saveUserInformation(String userInformation) { settingsRepository.updateSetting(USER_INFORMATION, userInformation); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void assertSaveUserInformationCallsRepositoryUpdate() { Mockito.doNothing().doNothing().when(settingsRepository).updateSetting(Mockito.anyString(), Mockito.anyString()); allSettings.saveUserInformation(""); Mockito.verify(settingsRepository, Mockito.times(1)).updateSetting(Mockito.anyString(), Mockito.anyString()); }
### Question: AllSettings { public String get(String key) { return get(key, null); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void testGetWithDefaultShouldReturnCorrectValue() { SettingsRepository settingsRepository = spy(new SettingsRepository()); allSettings = new AllSettings(allSharedPreferences, settingsRepository); String value = allSettings.get("non_existent_key", "default_value"); assertEquals("default_value", value); doReturn("value").when(settingsRepository).querySetting(eq("my_key"), any()); value = allSettings.get("my_key"); assertEquals("value", value); } @Test public void testGet() { Mockito.when(settingsRepository.querySetting("testKey", null)).thenReturn("testValue"); String val = allSettings.get("testKey"); Mockito.verify(settingsRepository).querySetting("testKey", null); Assert.assertEquals("testValue", val); }
### Question: AllSettings { public void put(String key, String value) { settingsRepository.updateSetting(key, value); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void testPut() { allSettings.put("testKey", "testValue"); Mockito.verify(settingsRepository).updateSetting("testKey", "testValue"); }
### Question: AllSettings { public Setting getSetting(String key) { return settingsRepository.querySetting(key); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void testGetSetting() { Setting s = new Setting(); s.setKey("testKey"); s.setValue("testValue"); Mockito.when(settingsRepository.querySetting("testKey")).thenReturn(s); Setting setting = allSettings.getSetting("testKey"); Mockito.verify(settingsRepository).querySetting("testKey"); Assert.assertEquals("testKey", setting.getKey()); Assert.assertEquals("testValue", setting.getValue()); }
### Question: AllSettings { public List<Setting> getSettingsByType(String type) { return settingsRepository.querySettingsByType(type); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void testGetSettingsByType() { List<Setting> ls = new ArrayList<>(); Setting s = new Setting(); s.setKey("testKey"); s.setValue("testValue"); ls.add(s); Setting s2 = new Setting(); s2.setKey("testKey2"); s2.setValue("testValue2"); ls.add(s2); Mockito.when(settingsRepository.querySettingsByType("testType")).thenReturn(ls); List<Setting> settings = allSettings.getSettingsByType("testType"); Mockito.verify(settingsRepository).querySettingsByType("testType"); Assert.assertEquals("testKey", settings.get(0).getKey()); Assert.assertEquals("testValue", settings.get(0).getValue()); }
### Question: AllSettings { public void putSetting(Setting setting) { settingsRepository.updateSetting(setting); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void testPutSetting() { Setting s = new Setting(); s.setKey("testKey"); s.setValue("testValue"); allSettings.putSetting(s); Mockito.verify(settingsRepository).updateSetting(s); }
### Question: AllSettings { public List<Setting> getUnsyncedSettings() { return settingsRepository.queryUnsyncedSettings(); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void testGetUnsyncedSettings() { List<Setting> ls = new ArrayList<>(); Setting s = new Setting(); s.setKey("testUnsyncedKey"); s.setValue("testUnsyncedValue"); ls.add(s); Mockito.when(settingsRepository.queryUnsyncedSettings()).thenReturn(ls); List<Setting> settings = allSettings.getUnsyncedSettings(); Mockito.verify(settingsRepository).queryUnsyncedSettings(); Assert.assertEquals("testUnsyncedKey", settings.get(0).getKey()); Assert.assertEquals("testUnsyncedValue", settings.get(0).getValue()); }
### Question: AllSettings { public AllSharedPreferences getPreferences() { return preferences; } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void testGetPreferences() { assertEquals(allSharedPreferences, allSettings.getPreferences()); }
### Question: AllSettings { public String fetchRegisteredANM() { return preferences.fetchRegisteredANM(); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void testFetchRegisteredANMShouldReturnCorrectProvider() { doReturn("provider").when(allSharedPreferences).fetchRegisteredANM(); assertEquals("provider", allSettings.fetchRegisteredANM()); }
### Question: AllSettings { public String fetchDefaultTeamId(String username) { return preferences.fetchDefaultTeamId(username); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void testFetchDefaultTeamIdShouldReturnCorrectTeamId() { doReturn("team-id").when(allSharedPreferences).fetchDefaultTeamId(anyString()); assertEquals("team-id", allSettings.fetchDefaultTeamId("user-name")); }
### Question: AllSettings { public String fetchDefaultTeam(String username) { return preferences.fetchDefaultTeam(username); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void testFetchDefaultTeamShouldReturnCorrectTeam() { doReturn("team").when(allSharedPreferences).fetchDefaultTeam(anyString()); assertEquals("team", allSettings.fetchDefaultTeam("user-name")); }
### Question: AllSettings { public String fetchDefaultLocalityId(String username) { return preferences.fetchDefaultLocalityId(username); } AllSettings(AllSharedPreferences preferences, SettingsRepository settingsRepository); void registerANM(String userName); void savePreviousFetchIndex(String value); String fetchPreviousFetchIndex(); void saveAppliedVillageFilter(String village); String appliedVillageFilter(String defaultFilterValue); String fetchPreviousFormSyncIndex(); void savePreviousFormSyncIndex(String value); void saveANMLocation(String anmLocation); void saveANMTeam(String anmTeam); String fetchANMLocation(); void saveUserInformation(String userInformation); String fetchUserInformation(); void put(String key, String value); String get(String key); String get(String key, String defaultValue); Setting getSetting(String key); List<Setting> getSettingsByType(String type); void putSetting(Setting setting); List<Setting> getUnsyncedSettings(); int getUnsyncedSettingsCount(); String fetchRegisteredANM(); String fetchDefaultTeamId(String username); String fetchDefaultTeam(String username); String fetchDefaultLocalityId(String username); AllSharedPreferences getPreferences(); static final String APPLIED_VILLAGE_FILTER_SETTING_KEY; static final String PREVIOUS_FETCH_INDEX_SETTING_KEY; static final String PREVIOUS_FORM_SYNC_INDEX_SETTING_KEY; }### Answer: @Test public void testFetchDefaultLocalityIdShouldReturnCorrectLocalityId() { doReturn("locality").when(allSharedPreferences).fetchDefaultLocalityId(anyString()); assertEquals("locality", allSettings.fetchDefaultLocalityId("user-name")); }
### Question: LocationTagRepository extends BaseRepository { public void addOrUpdate(LocationTag locationTag) { if (StringUtils.isBlank(locationTag.getLocationId())) throw new IllegalArgumentException("location id not provided"); ContentValues contentValues = new ContentValues(); contentValues.put(NAME, locationTag.getName()); contentValues.put(LOCATION_ID, locationTag.getLocationId()); getWritableDatabase().replace(getLocationTagTableName(), null, contentValues); } static void createTable(SQLiteDatabase database); void addOrUpdate(LocationTag locationTag); List<LocationTag> getAllLocationTags(); List<LocationTag> getLocationTagByLocationId(String id); List<LocationTag> getLocationTagsByTagName(String tagName); }### Answer: @Test public void testAddOrUpdateShouldAdd() { LocationTag locationTag = gson.fromJson(locationTagJson, LocationTag.class); locationTagRepository.addOrUpdate(locationTag); verify(sqLiteDatabase).replace(stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), contentValuesArgumentCaptor.capture()); assertEquals(2, stringArgumentCaptor.getAllValues().size()); Iterator<String> iterator = stringArgumentCaptor.getAllValues().iterator(); assertEquals(LOCATION_TAG_TABLE, iterator.next()); assertNull(iterator.next()); ContentValues contentValues = contentValuesArgumentCaptor.getValue(); assertEquals(2, contentValues.size()); assertEquals("Facility", contentValues.getAsString("name")); assertEquals("1", contentValues.getAsString("location_id")); } @Test(expected = IllegalArgumentException.class) public void testAddOrUpdateShouldThrowException() { LocationTag locationTag = new LocationTag(); locationTagRepository.addOrUpdate(locationTag); }
### Question: LocationTagRepository extends BaseRepository { public List<LocationTag> getAllLocationTags() { Cursor cursor = null; List<LocationTag> locationsTags = new ArrayList<>(); try { cursor = getReadableDatabase().rawQuery("SELECT * FROM " + getLocationTagTableName(), null); while (cursor.moveToNext()) { locationsTags.add(readCursor(cursor)); } cursor.close(); } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return locationsTags; } static void createTable(SQLiteDatabase database); void addOrUpdate(LocationTag locationTag); List<LocationTag> getAllLocationTags(); List<LocationTag> getLocationTagByLocationId(String id); List<LocationTag> getLocationTagsByTagName(String tagName); }### Answer: @Test public void tesGetAllLocationTags() { when(sqLiteDatabase.rawQuery("SELECT * FROM " + LOCATION_TAG_TABLE, null)).thenReturn(getCursor()); List<LocationTag> allLocationsTags = locationTagRepository.getAllLocationTags(); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals("SELECT * FROM location_tag", stringArgumentCaptor.getValue()); assertEquals(1, allLocationsTags.size()); LocationTag locationTag = allLocationsTags.get(0); assertEquals(locationTagJson, stripTimezone(gson.toJson(locationTag))); }
### Question: LocationTagRepository extends BaseRepository { public List<LocationTag> getLocationTagByLocationId(String id) { List<LocationTag> locationsTags = new ArrayList<>(); try (Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + getLocationTagTableName() + " WHERE " + LOCATION_ID + " =?", new String[]{id})) { while (cursor.moveToNext()) { locationsTags.add(readCursor(cursor)); } } catch (Exception e) { Timber.e(e); } return locationsTags; } static void createTable(SQLiteDatabase database); void addOrUpdate(LocationTag locationTag); List<LocationTag> getAllLocationTags(); List<LocationTag> getLocationTagByLocationId(String id); List<LocationTag> getLocationTagsByTagName(String tagName); }### Answer: @Test public void testGetLocationTagsById() { when(sqLiteDatabase.rawQuery("SELECT * FROM " + LOCATION_TAG_TABLE + " WHERE " + LOCATION_ID + " =?", new String[]{"1"})).thenReturn(getCursor()); List<LocationTag> locationTags = locationTagRepository.getLocationTagByLocationId("1"); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals("SELECT * FROM " + LOCATION_TAG_TABLE + " WHERE " + LOCATION_ID + " =?", stringArgumentCaptor.getValue()); assertEquals(1, argsCaptor.getValue().length); assertEquals("1", argsCaptor.getValue()[0]); assertEquals(locationTagJson, stripTimezone(gson.toJson(locationTags.get(0)))); }
### Question: LocationTagRepository extends BaseRepository { public List<LocationTag> getLocationTagsByTagName(String tagName) { List<LocationTag> locationTags = new ArrayList<>(); try (Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + getLocationTagTableName() + " WHERE " + NAME + " =?", new String[]{tagName})) { while (cursor.moveToNext()) { locationTags.add(readCursor(cursor)); } } catch (Exception e) { Timber.e(e); } return locationTags; } static void createTable(SQLiteDatabase database); void addOrUpdate(LocationTag locationTag); List<LocationTag> getAllLocationTags(); List<LocationTag> getLocationTagByLocationId(String id); List<LocationTag> getLocationTagsByTagName(String tagName); }### Answer: @Test public void testGetLocationTagsByTagName() { when(sqLiteDatabase.rawQuery("SELECT * FROM " + LOCATION_TAG_TABLE + " WHERE " + NAME + " =?", new String[]{"Facility"})).thenReturn(getCursor()); List<LocationTag> locationTags = locationTagRepository.getLocationTagsByTagName("Facility"); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals("SELECT * FROM " + LOCATION_TAG_TABLE + " WHERE " + NAME + " =?", stringArgumentCaptor.getValue()); assertEquals(1, argsCaptor.getValue().length); assertEquals("Facility", argsCaptor.getValue()[0]); assertEquals(locationTagJson, stripTimezone(gson.toJson(locationTags.get(0)))); }
### Question: EligibleCoupleRepository extends DrishtiRepository { @Override protected void onCreate(SQLiteDatabase database) { database.execSQL(EC_SQL); } void add(EligibleCouple eligibleCouple); void updateDetails(String caseId, Map<String, String> details); void mergeDetails(String caseId, Map<String, String> details); List<EligibleCouple> allEligibleCouples(); List<EligibleCouple> findByCaseIDs(String... caseIds); EligibleCouple findByCaseID(String caseId); long count(); List<String> villages(); void updatePhotoPath(String caseId, String imagePath); void close(String caseId); long fpCount(); static final String ID_COLUMN; static final String EC_NUMBER_COLUMN; static final String WIFE_NAME_COLUMN; static final String HUSBAND_NAME_COLUMN; static final String VILLAGE_NAME_COLUMN; static final String SUBCENTER_NAME_COLUMN; static final String IS_OUT_OF_AREA_COLUMN; static final String DETAILS_COLUMN; static final String PHOTO_PATH_COLUMN; static final String EC_TABLE_NAME; static final String NOT_CLOSED; static final String[] EC_TABLE_COLUMNS; }### Answer: @Test public void assertOnCreateCallDatabaseExecSql() { eligibleCoupleRepository.onCreate(sqLiteDatabase); Mockito.verify(sqLiteDatabase, Mockito.times(1)).execSQL(Mockito.anyString()); }
### Question: EligibleCoupleRepository extends DrishtiRepository { public void close(String caseId) { ContentValues values = new ContentValues(); values.put(IS_CLOSED_COLUMN, TRUE.toString()); masterRepository.getWritableDatabase() .update(EC_TABLE_NAME, values, ID_COLUMN + " = ?", new String[]{caseId}); } void add(EligibleCouple eligibleCouple); void updateDetails(String caseId, Map<String, String> details); void mergeDetails(String caseId, Map<String, String> details); List<EligibleCouple> allEligibleCouples(); List<EligibleCouple> findByCaseIDs(String... caseIds); EligibleCouple findByCaseID(String caseId); long count(); List<String> villages(); void updatePhotoPath(String caseId, String imagePath); void close(String caseId); long fpCount(); static final String ID_COLUMN; static final String EC_NUMBER_COLUMN; static final String WIFE_NAME_COLUMN; static final String HUSBAND_NAME_COLUMN; static final String VILLAGE_NAME_COLUMN; static final String SUBCENTER_NAME_COLUMN; static final String IS_OUT_OF_AREA_COLUMN; static final String DETAILS_COLUMN; static final String PHOTO_PATH_COLUMN; static final String EC_TABLE_NAME; static final String NOT_CLOSED; static final String[] EC_TABLE_COLUMNS; }### Answer: @Test public void assertCloseCallsUpdate() { eligibleCoupleRepository.updateMasterRepository(repository); Mockito.when(repository.getWritableDatabase()).thenReturn(sqLiteDatabase); Mockito.when(sqLiteDatabase.update(Mockito.anyString(), Mockito.any(ContentValues.class), Mockito.anyString(), Mockito.any(String[].class))).thenReturn(1); eligibleCoupleRepository.close("0"); Mockito.verify(sqLiteDatabase, Mockito.times(1)).update(Mockito.anyString(), Mockito.any(ContentValues.class), Mockito.anyString(), Mockito.any(String[].class)); }
### Question: EligibleCoupleRepository extends DrishtiRepository { public void add(EligibleCouple eligibleCouple) { SQLiteDatabase database = masterRepository.getWritableDatabase(); database.insert(EC_TABLE_NAME, null, createValuesFor(eligibleCouple)); } void add(EligibleCouple eligibleCouple); void updateDetails(String caseId, Map<String, String> details); void mergeDetails(String caseId, Map<String, String> details); List<EligibleCouple> allEligibleCouples(); List<EligibleCouple> findByCaseIDs(String... caseIds); EligibleCouple findByCaseID(String caseId); long count(); List<String> villages(); void updatePhotoPath(String caseId, String imagePath); void close(String caseId); long fpCount(); static final String ID_COLUMN; static final String EC_NUMBER_COLUMN; static final String WIFE_NAME_COLUMN; static final String HUSBAND_NAME_COLUMN; static final String VILLAGE_NAME_COLUMN; static final String SUBCENTER_NAME_COLUMN; static final String IS_OUT_OF_AREA_COLUMN; static final String DETAILS_COLUMN; static final String PHOTO_PATH_COLUMN; static final String EC_TABLE_NAME; static final String NOT_CLOSED; static final String[] EC_TABLE_COLUMNS; }### Answer: @Test public void assertAddECCallsDatabaseSqlInsert() { eligibleCoupleRepository.updateMasterRepository(repository); Mockito.when(repository.getWritableDatabase()).thenReturn(sqLiteDatabase); eligibleCoupleRepository.add(getMockEligibleCouple()); Mockito.verify(sqLiteDatabase, Mockito.times(1)).insert(Mockito.anyString(), Mockito.isNull(String.class), Mockito.any(ContentValues.class)); }
### Question: ClientFormRepository extends BaseRepository implements ClientFormContract.Dao { public ClientForm getActiveClientFormByIdentifier(String identifier) { try (Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + getClientFormTableName() + " WHERE " + IDENTIFIER + " =? AND " + ACTIVE + " = 1", new String[]{identifier})) { if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } return null; } static void createTable(SQLiteDatabase database); @Override void addOrUpdate(ClientFormContract.Model clientForm); @Override void setIsNew(boolean isNew, int formId); @Override List<ClientFormContract.Model> getClientFormByIdentifier(String identifier); ClientForm getActiveClientFormByIdentifier(String identifier); @Override ClientForm getLatestFormByIdentifier(String identifier); @Override void delete(int clientFormId); @Override ClientFormContract.Model createNewClientFormModel(); static final String CREATE_CLIENT_FORM_TABLE; }### Answer: @Test public void testGetActiveClientFormByIdentifier() { String identifier = "en/child/enrollment.json"; clientFormRepository.getActiveClientFormByIdentifier(identifier); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals("SELECT * FROM " + CLIENT_FORM_TABLE + " WHERE " + IDENTIFIER + " =? AND " + ACTIVE + " = 1", stringArgumentCaptor.getValue()); assertEquals(1, argsCaptor.getValue().length); assertEquals(identifier, argsCaptor.getValue()[0]); }
### Question: ClientFormRepository extends BaseRepository implements ClientFormContract.Dao { @Override public List<ClientFormContract.Model> getClientFormByIdentifier(String identifier) { List<ClientFormContract.Model> clientForms = new ArrayList<>(); try (Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + getClientFormTableName() + " WHERE " + IDENTIFIER + " =? ORDER BY " + CREATED_AT + " DESC", new String[]{identifier})) { while (cursor.moveToNext()) { clientForms.add(readCursor(cursor)); } } catch (Exception e) { Timber.e(e); } return clientForms; } static void createTable(SQLiteDatabase database); @Override void addOrUpdate(ClientFormContract.Model clientForm); @Override void setIsNew(boolean isNew, int formId); @Override List<ClientFormContract.Model> getClientFormByIdentifier(String identifier); ClientForm getActiveClientFormByIdentifier(String identifier); @Override ClientForm getLatestFormByIdentifier(String identifier); @Override void delete(int clientFormId); @Override ClientFormContract.Model createNewClientFormModel(); static final String CREATE_CLIENT_FORM_TABLE; }### Answer: @Test public void testGetClientFormByIdentifier() { String identifier = "en/child/enrollment.json"; clientFormRepository.getClientFormByIdentifier(identifier); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals("SELECT * FROM " + CLIENT_FORM_TABLE + " WHERE " + IDENTIFIER + " =? ORDER BY " + CREATED_AT + " DESC", stringArgumentCaptor.getValue()); assertEquals(1, argsCaptor.getValue().length); assertEquals(identifier, argsCaptor.getValue()[0]); }
### Question: ClientFormRepository extends BaseRepository implements ClientFormContract.Dao { @Override public ClientForm getLatestFormByIdentifier(String identifier) { try (Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM " + getClientFormTableName() + " WHERE " + IDENTIFIER + " = ? ORDER BY " + CREATED_AT + " DESC LIMIT 1", new String[]{identifier})) { if (cursor.moveToFirst()) { return readCursor(cursor); } } catch (Exception e) { Timber.e(e); } return null; } static void createTable(SQLiteDatabase database); @Override void addOrUpdate(ClientFormContract.Model clientForm); @Override void setIsNew(boolean isNew, int formId); @Override List<ClientFormContract.Model> getClientFormByIdentifier(String identifier); ClientForm getActiveClientFormByIdentifier(String identifier); @Override ClientForm getLatestFormByIdentifier(String identifier); @Override void delete(int clientFormId); @Override ClientFormContract.Model createNewClientFormModel(); static final String CREATE_CLIENT_FORM_TABLE; }### Answer: @Test public void testGetLatestFormByIdentifier() { String identifier = "en/child/enrollment.json"; clientFormRepository.getLatestFormByIdentifier(identifier); verify(sqLiteDatabase).rawQuery(stringArgumentCaptor.capture(), argsCaptor.capture()); assertEquals("SELECT * FROM " + CLIENT_FORM_TABLE + " WHERE " + IDENTIFIER + " = ? ORDER BY " + CREATED_AT + " DESC LIMIT 1", stringArgumentCaptor.getValue()); assertEquals(1, argsCaptor.getValue().length); assertEquals(identifier, argsCaptor.getValue()[0]); }
### Question: ClientFormRepository extends BaseRepository implements ClientFormContract.Dao { @Override public void setIsNew(boolean isNew, int formId) { ContentValues contentValues = new ContentValues(); contentValues.put(ID, formId); contentValues.put(IS_NEW, isNew); getWritableDatabase().update(getClientFormTableName(),contentValues, ID + " = ?", new String[]{String.valueOf(formId)}); } static void createTable(SQLiteDatabase database); @Override void addOrUpdate(ClientFormContract.Model clientForm); @Override void setIsNew(boolean isNew, int formId); @Override List<ClientFormContract.Model> getClientFormByIdentifier(String identifier); ClientForm getActiveClientFormByIdentifier(String identifier); @Override ClientForm getLatestFormByIdentifier(String identifier); @Override void delete(int clientFormId); @Override ClientFormContract.Model createNewClientFormModel(); static final String CREATE_CLIENT_FORM_TABLE; }### Answer: @Test public void testSetIsNewShouldCallDatabaseUpdateWithCorrectValues() { ArgumentCaptor<ContentValues> argumentCaptor = ArgumentCaptor.forClass(ContentValues.class); ArgumentCaptor<String[]> stringArgumentCaptor = ArgumentCaptor.forClass(String[].class); clientFormRepository.setIsNew(false, 56); verify(sqLiteDatabase).update(eq("client_form"), argumentCaptor.capture(), eq("id = ?"), stringArgumentCaptor.capture()); ContentValues contentValues = argumentCaptor.getValue(); assertEquals(false, contentValues.getAsBoolean(ClientFormRepository.IS_NEW)); assertEquals(56, (int) contentValues.getAsInteger(ClientFormRepository.ID)); String[] whereArgs = stringArgumentCaptor.getValue(); assertEquals("56", whereArgs[0]); }
### Question: ReportRepository extends DrishtiRepository { @Override protected void onCreate(SQLiteDatabase database) { database.execSQL(REPORT_SQL); database.execSQL(REPORT_INDICATOR_INDEX_SQL); } void update(Report report); List<Report> allFor(String... indicators); List<Report> all(); }### Answer: @Test public void onCreateCallsDatabaseExec() { reportRepository.onCreate(sqLiteDatabase); Mockito.verify(sqLiteDatabase, Mockito.times(2)).execSQL(Mockito.anyString()); }
### Question: ReportRepository extends DrishtiRepository { public void update(Report report) { SQLiteDatabase database = masterRepository.getWritableDatabase(); database.replace(REPORT_TABLE_NAME, null, createValuesFor(report)); } void update(Report report); List<Report> allFor(String... indicators); List<Report> all(); }### Answer: @Test public void assertUpdateCallsDatabaseUpdate() { Report report = new Report("", "", ""); reportRepository.update(report); Mockito.verify(sqLiteDatabase, Mockito.times(1)).replace(Mockito.anyString(), Mockito.isNull(String.class), Mockito.any(ContentValues.class)); }
### Question: ReportRepository extends DrishtiRepository { public List<Report> allFor(String... indicators) { SQLiteDatabase database = masterRepository.getReadableDatabase(); Cursor cursor = database.rawQuery( String.format("SELECT * FROM %s WHERE %s IN (%s)", REPORT_TABLE_NAME, INDICATOR_COLUMN, insertPlaceholdersForInClause(indicators.length)), indicators); return readAll(cursor); } void update(Report report); List<Report> allFor(String... indicators); List<Report> all(); }### Answer: @Test public void assertAllForReturnsReportList() { String[] columns = {"a", "b", "c"}; MatrixCursor cursor = new MatrixCursor(columns); cursor.addRow(new Object[]{"", "", ""}); Mockito.when(sqLiteDatabase.rawQuery(Mockito.anyString(), Mockito.any(String[].class))).thenReturn(cursor); Assert.assertNotNull(reportRepository.allFor("", "", "")); }
### Question: ReportRepository extends DrishtiRepository { public List<Report> all() { SQLiteDatabase database = masterRepository.getReadableDatabase(); Cursor cursor = database .query(REPORT_TABLE_NAME, REPORT_TABLE_COLUMNS, null, null, null, null, null); return readAll(cursor); } void update(Report report); List<Report> allFor(String... indicators); List<Report> all(); }### Answer: @Test public void assertAllReturnsAllReports() { String[] columns = {"a", "b", "c"}; MatrixCursor cursor = new MatrixCursor(columns); cursor.addRow(new Object[]{"", "", ""}); Mockito.when(sqLiteDatabase.query(REPORT_TABLE_NAME, REPORT_TABLE_COLUMNS, null, null, null, null, null)).thenReturn(cursor); Assert.assertNotNull(reportRepository.all()); }
### Question: ImageRepository extends DrishtiRepository { @Override protected void onCreate(SQLiteDatabase database) { database.execSQL(Image_SQL); database.execSQL(ENTITY_ID_INDEX); } void add(ProfileImage Image); List<ProfileImage> allProfileImages(); @Nullable HashMap<String, Object> getImage(long lastRowId); ProfileImage findByEntityId(String entityId); List<ProfileImage> findAllUnSynced(); void close(String caseId); static final String Image_TABLE_NAME; static final String ID_COLUMN; static final String anm_ID_COLUMN; static final String entityID_COLUMN; static final String filepath_COLUMN; static final String syncStatus_COLUMN; static final String filecategory_COLUMN; static final String TYPE_ANC; static final String TYPE_PNC; static final String[] Image_TABLE_COLUMNS; static String TYPE_Unsynced; static String TYPE_Synced; }### Answer: @Test public void assertOnCrateCallsDatabaseExec() { imageRepository.onCreate(sqLiteDatabase); Mockito.verify(sqLiteDatabase, Mockito.times(2)).execSQL(Mockito.anyString()); }
### Question: ImageRepository extends DrishtiRepository { public void add(ProfileImage Image) { SQLiteDatabase database = masterRepository.getWritableDatabase(); database.insert(Image_TABLE_NAME, null, createValuesFor(Image, TYPE_ANC)); } void add(ProfileImage Image); List<ProfileImage> allProfileImages(); @Nullable HashMap<String, Object> getImage(long lastRowId); ProfileImage findByEntityId(String entityId); List<ProfileImage> findAllUnSynced(); void close(String caseId); static final String Image_TABLE_NAME; static final String ID_COLUMN; static final String anm_ID_COLUMN; static final String entityID_COLUMN; static final String filepath_COLUMN; static final String syncStatus_COLUMN; static final String filecategory_COLUMN; static final String TYPE_ANC; static final String TYPE_PNC; static final String[] Image_TABLE_COLUMNS; static String TYPE_Unsynced; static String TYPE_Synced; }### Answer: @Test public void assertAddCallsDatabaseInsert() { imageRepository.add(getProfileImage()); Mockito.verify(sqLiteDatabase, Mockito.times(1)).insert(Mockito.anyString(), Mockito.isNull(String.class), Mockito.any(ContentValues.class)); }
### Question: ImageRepository extends DrishtiRepository { public List<ProfileImage> allProfileImages() { SQLiteDatabase database = masterRepository.getReadableDatabase(); Cursor cursor = database .query(Image_TABLE_NAME, Image_TABLE_COLUMNS, syncStatus_COLUMN + " = ?", new String[]{TYPE_Unsynced}, null, null, null, null); return readAll(cursor); } void add(ProfileImage Image); List<ProfileImage> allProfileImages(); @Nullable HashMap<String, Object> getImage(long lastRowId); ProfileImage findByEntityId(String entityId); List<ProfileImage> findAllUnSynced(); void close(String caseId); static final String Image_TABLE_NAME; static final String ID_COLUMN; static final String anm_ID_COLUMN; static final String entityID_COLUMN; static final String filepath_COLUMN; static final String syncStatus_COLUMN; static final String filecategory_COLUMN; static final String TYPE_ANC; static final String TYPE_PNC; static final String[] Image_TABLE_COLUMNS; static String TYPE_Unsynced; static String TYPE_Synced; }### Answer: @Test public void assertallProfileImages() { Mockito.when(sqLiteDatabase.query(Mockito.anyString(), Mockito.any(String[].class), Mockito.anyString(), Mockito.any(String[].class), Mockito.isNull(String.class), Mockito.isNull(String.class), Mockito.isNull(String.class), Mockito.isNull(String.class))).thenReturn(getCursor()); Assert.assertNotNull(imageRepository.allProfileImages()); }
### Question: ImageRepository extends DrishtiRepository { public void close(String caseId) { ContentValues values = new ContentValues(); values.put(syncStatus_COLUMN, TYPE_Synced); masterRepository.getWritableDatabase() .update(Image_TABLE_NAME, values, ID_COLUMN + " = ?", new String[]{caseId}); } void add(ProfileImage Image); List<ProfileImage> allProfileImages(); @Nullable HashMap<String, Object> getImage(long lastRowId); ProfileImage findByEntityId(String entityId); List<ProfileImage> findAllUnSynced(); void close(String caseId); static final String Image_TABLE_NAME; static final String ID_COLUMN; static final String anm_ID_COLUMN; static final String entityID_COLUMN; static final String filepath_COLUMN; static final String syncStatus_COLUMN; static final String filecategory_COLUMN; static final String TYPE_ANC; static final String TYPE_PNC; static final String[] Image_TABLE_COLUMNS; static String TYPE_Unsynced; static String TYPE_Synced; }### Answer: @Test public void assertclose() { imageRepository.close("1"); Mockito.verify(sqLiteDatabase, Mockito.times(1)).update(Mockito.anyString(), Mockito.any(ContentValues.class), Mockito.anyString(), Mockito.any(String[].class)); }
### Question: ImageRepository extends DrishtiRepository { public List<ProfileImage> findAllUnSynced() { SQLiteDatabase database = masterRepository.getReadableDatabase(); Cursor cursor = database .query(Image_TABLE_NAME, Image_TABLE_COLUMNS, syncStatus_COLUMN + " = ?", new String[]{TYPE_Unsynced}, null, null, null, null); return readAll(cursor); } void add(ProfileImage Image); List<ProfileImage> allProfileImages(); @Nullable HashMap<String, Object> getImage(long lastRowId); ProfileImage findByEntityId(String entityId); List<ProfileImage> findAllUnSynced(); void close(String caseId); static final String Image_TABLE_NAME; static final String ID_COLUMN; static final String anm_ID_COLUMN; static final String entityID_COLUMN; static final String filepath_COLUMN; static final String syncStatus_COLUMN; static final String filecategory_COLUMN; static final String TYPE_ANC; static final String TYPE_PNC; static final String[] Image_TABLE_COLUMNS; static String TYPE_Unsynced; static String TYPE_Synced; }### Answer: @Test public void assertfindAllUnSynced() { Mockito.when(sqLiteDatabase.query(Mockito.anyString(), Mockito.any(String[].class), Mockito.anyString(), Mockito.any(String[].class), Mockito.isNull(String.class), Mockito.isNull(String.class), Mockito.isNull(String.class), Mockito.isNull(String.class))).thenReturn(getCursor()); Assert.assertNotNull(imageRepository.findAllUnSynced()); }
### Question: ImageRepository extends DrishtiRepository { public ProfileImage findByEntityId(String entityId) { SQLiteDatabase database = masterRepository.getReadableDatabase(); Cursor cursor = database.query(Image_TABLE_NAME, Image_TABLE_COLUMNS, entityID_COLUMN + " = ? COLLATE NOCASE ", new String[]{entityId}, null, null, null, null); List<ProfileImage> profileImages = readAll(cursor); return profileImages.isEmpty() ? null : profileImages.get(0); } void add(ProfileImage Image); List<ProfileImage> allProfileImages(); @Nullable HashMap<String, Object> getImage(long lastRowId); ProfileImage findByEntityId(String entityId); List<ProfileImage> findAllUnSynced(); void close(String caseId); static final String Image_TABLE_NAME; static final String ID_COLUMN; static final String anm_ID_COLUMN; static final String entityID_COLUMN; static final String filepath_COLUMN; static final String syncStatus_COLUMN; static final String filecategory_COLUMN; static final String TYPE_ANC; static final String TYPE_PNC; static final String[] Image_TABLE_COLUMNS; static String TYPE_Unsynced; static String TYPE_Synced; }### Answer: @Test public void assertfindByEntityId() { Mockito.when(sqLiteDatabase.query(Mockito.anyString(), Mockito.any(String[].class), Mockito.anyString(), Mockito.any(String[].class), Mockito.isNull(String.class), Mockito.isNull(String.class), Mockito.isNull(String.class), Mockito.isNull(String.class))).thenReturn(getCursor()); Assert.assertNotNull(imageRepository.findByEntityId("1")); }
### Question: EventRepository extends SQLiteOpenHelper { @Override public void onCreate(SQLiteDatabase database) { database.execSQL(common_SQL); } EventRepository(Context context, String[] columns); EventRepository(Context context, String tableName, String[] columns); @Override void onOpen(SQLiteDatabase db); @Override void onCreate(SQLiteDatabase database); @Override void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1); ContentValues createValuesFor(Event common); void insertValues(ContentValues values); static final String ID_COLUMN; static final String Relational_ID; static final String obsDETAILS_COLUMN; static final String attributeDETAILS_COLUMN; public String TABLE_NAME; public String[] additionalcolumns; }### Answer: @Test public void constructorNotNullCallsOnCreateDatabaseExec() { Assert.assertNotNull(eventRepository); eventRepository.onCreate(sqLiteDatabase); Mockito.verify(sqLiteDatabase, Mockito.times(1)).execSQL(Mockito.anyString()); }
### Question: EventRepository extends SQLiteOpenHelper { public ContentValues createValuesFor(Event common) { ContentValues values = new ContentValues(); values.put(Relational_ID, common.getBaseEntityID()); values.put(obsDETAILS_COLUMN, new Gson().toJson(common.getObsDetailsMap())); values.put(attributeDETAILS_COLUMN, new Gson().toJson(common.getAttributesDetailsMap())); for (Map.Entry<String, String> entry : common.getAttributesColumnsMap().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); values.put(key, value); } for (Map.Entry<String, String> entry : common.getObsColumnsMap().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); values.put(key, value); } return values; } EventRepository(Context context, String[] columns); EventRepository(Context context, String tableName, String[] columns); @Override void onOpen(SQLiteDatabase db); @Override void onCreate(SQLiteDatabase database); @Override void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1); ContentValues createValuesFor(Event common); void insertValues(ContentValues values); static final String ID_COLUMN; static final String Relational_ID; static final String obsDETAILS_COLUMN; static final String attributeDETAILS_COLUMN; public String TABLE_NAME; public String[] additionalcolumns; }### Answer: @Test public void assertcreateValuesForReturnsContentValues() { HashMap<String, String> mockmap = new HashMap<>(); mockmap.put("key", "value"); Event common = new Event(Relational_ID, mockmap, mockmap, mockmap, mockmap); Assert.assertNotNull(eventRepository.createValuesFor(common)); }
### Question: ServiceProvidedRepository extends DrishtiRepository { @Override protected void onCreate(SQLiteDatabase database) { database.execSQL(SERVICE_PROVIDED_SQL); } void add(ServiceProvided serviceProvided); List<ServiceProvided> findByEntityIdAndServiceNames(String entityId, String... names); List<ServiceProvided> all(); static final String SERVICE_PROVIDED_TABLE_NAME; static final String ENTITY_ID_COLUMN; static final String NAME_ID_COLUMN; static final String DATE_ID_COLUMN; static final String DATA_ID_COLUMN; static final String[] SERVICE_PROVIDED_TABLE_COLUMNS; }### Answer: @Test public void ssertOnCreateCallsDatabaseExec() { serviceProvidedRepository.onCreate(sqLiteDatabase); Mockito.verify(sqLiteDatabase, Mockito.times(1)).execSQL(Mockito.anyString()); }
### Question: ServiceProvidedRepository extends DrishtiRepository { public void add(ServiceProvided serviceProvided) { SQLiteDatabase database = masterRepository.getWritableDatabase(); database.insert(SERVICE_PROVIDED_TABLE_NAME, null, createValuesFor(serviceProvided)); } void add(ServiceProvided serviceProvided); List<ServiceProvided> findByEntityIdAndServiceNames(String entityId, String... names); List<ServiceProvided> all(); static final String SERVICE_PROVIDED_TABLE_NAME; static final String ENTITY_ID_COLUMN; static final String NAME_ID_COLUMN; static final String DATE_ID_COLUMN; static final String DATA_ID_COLUMN; static final String[] SERVICE_PROVIDED_TABLE_COLUMNS; }### Answer: @Test public void assertadCallsDatabaseInsert() { ServiceProvided serviceProvided = new ServiceProvided("", "", "", new HashMap<String, String>()); serviceProvidedRepository.add(serviceProvided); Mockito.verify(sqLiteDatabase, Mockito.times(1)).insert(Mockito.anyString(), Mockito.isNull(String.class), Mockito.any(ContentValues.class)); }
### Question: ServiceProvidedRepository extends DrishtiRepository { public List<ServiceProvided> findByEntityIdAndServiceNames(String entityId, String... names) { SQLiteDatabase database = masterRepository.getReadableDatabase(); Cursor cursor = database.rawQuery( format("SELECT * FROM %s WHERE %s = ? AND %s IN (%s) " + "ORDER BY " + "DATE" + "(%s)", SERVICE_PROVIDED_TABLE_NAME, ENTITY_ID_COLUMN, NAME_ID_COLUMN, insertPlaceholdersForInClause(names.length), DATE_ID_COLUMN), addAll(new String[]{entityId}, names)); return readAllServicesProvided(cursor); } void add(ServiceProvided serviceProvided); List<ServiceProvided> findByEntityIdAndServiceNames(String entityId, String... names); List<ServiceProvided> all(); static final String SERVICE_PROVIDED_TABLE_NAME; static final String ENTITY_ID_COLUMN; static final String NAME_ID_COLUMN; static final String DATE_ID_COLUMN; static final String DATA_ID_COLUMN; static final String[] SERVICE_PROVIDED_TABLE_COLUMNS; }### Answer: @Test public void assertAllfindByEntityIdAndServiceNames() { Mockito.when(sqLiteDatabase.rawQuery(Mockito.anyString(), Mockito.any(String[].class))).thenReturn(getCursor()); Assert.assertNotNull(serviceProvidedRepository.findByEntityIdAndServiceNames(ENTITY_ID_COLUMN, "a", "b")); }
### Question: ServiceProvidedRepository extends DrishtiRepository { public List<ServiceProvided> all() { SQLiteDatabase database = masterRepository.getReadableDatabase(); Cursor cursor = database .query(SERVICE_PROVIDED_TABLE_NAME, SERVICE_PROVIDED_TABLE_COLUMNS, null, null, null, null, DATE_ID_COLUMN); return readAllServicesProvided(cursor); } void add(ServiceProvided serviceProvided); List<ServiceProvided> findByEntityIdAndServiceNames(String entityId, String... names); List<ServiceProvided> all(); static final String SERVICE_PROVIDED_TABLE_NAME; static final String ENTITY_ID_COLUMN; static final String NAME_ID_COLUMN; static final String DATE_ID_COLUMN; static final String DATA_ID_COLUMN; static final String[] SERVICE_PROVIDED_TABLE_COLUMNS; }### Answer: @Test public void assertAllReturnsList() { Mockito.when(sqLiteDatabase.query(Mockito.anyString(), Mockito.any(String[].class), Mockito.isNull(String.class), Mockito.isNull(String[].class), Mockito.isNull(String.class), Mockito.isNull(String.class), Mockito.anyString())).thenReturn(getCursor()); Assert.assertNotNull(serviceProvidedRepository.all()); }
### Question: UniqueIdRepository extends BaseRepository { public Long countUnUsedIds() { long count = 0; Cursor cursor = null; try { cursor = getWritableDatabase().rawQuery("SELECT COUNT (*) FROM " + UniqueIds_TABLE_NAME + " WHERE " + STATUS_COLUMN + "=?", new String[]{STATUS_NOT_USED}); if (null != cursor && cursor.getCount() > 0) { cursor.moveToFirst(); count = cursor.getInt(0); } } catch (SQLException e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return count; } static void createTable(SQLiteDatabase database); void add(UniqueId uniqueId); void bulkInsertOpenmrsIds(List<String> ids); Long countUnUsedIds(); UniqueId getNextUniqueId(); int close(String openmrsId); int reserve(String uniqueId); int releaseReservedIds(); int open(String openmrsId); }### Answer: @Test public void testCountUnusedIds() { when(sqLiteDatabase.rawQuery(anyString(), any())).thenReturn(getCountCursor()); long actualCount = uniqueIdRepository.countUnUsedIds(); assertEquals(12, actualCount); verify(sqLiteDatabase).rawQuery("SELECT COUNT (*) FROM unique_ids WHERE status=?", new String[]{"not_used"}); }
### Question: UniqueIdRepository extends BaseRepository { public UniqueId getNextUniqueId() { UniqueId uniqueId = null; Cursor cursor = null; try { cursor = getReadableDatabase().query(UniqueIds_TABLE_NAME, UniqueIds_TABLE_COLUMNS, STATUS_COLUMN + " = ?", new String[]{STATUS_NOT_USED}, null, null, CREATED_AT_COLUMN + " ASC", "1"); List<UniqueId> ids = readAll(cursor); uniqueId = ids.isEmpty() ? null : ids.get(0); } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) { cursor.close(); } } if (uniqueId != null) { reserve(uniqueId.getOpenmrsId()); } return uniqueId; } static void createTable(SQLiteDatabase database); void add(UniqueId uniqueId); void bulkInsertOpenmrsIds(List<String> ids); Long countUnUsedIds(); UniqueId getNextUniqueId(); int close(String openmrsId); int reserve(String uniqueId); int releaseReservedIds(); int open(String openmrsId); }### Answer: @Test public void testGetNextUniqueId() { when(sqLiteDatabase.query(any(), any(), any(), any(), any(), any(), anyString(), anyString())).thenReturn(getUniqueIdCursor()); UniqueId actualUniqueId = uniqueIdRepository.getNextUniqueId(); assertEquals("12", actualUniqueId.getId()); assertEquals("openrs-id1", actualUniqueId.getOpenmrsId()); assertEquals("test-owner", actualUniqueId.getUsedBy()); assertEquals(new Date(1583830167).toString(), actualUniqueId.getCreatedAt().toString()); }
### Question: UniqueIdRepository extends BaseRepository { private ContentValues createValuesFor(UniqueId uniqueId) { ContentValues values = new ContentValues(); values.put(ID_COLUMN, uniqueId.getId()); values.put(OPENMRS_ID_COLUMN, uniqueId.getOpenmrsId()); values.put(STATUS_COLUMN, uniqueId.getStatus()); values.put(USED_BY_COLUMN, uniqueId.getUsedBy()); values.put(CREATED_AT_COLUMN, dateFormat.format(uniqueId.getCreatedAt())); return values; } static void createTable(SQLiteDatabase database); void add(UniqueId uniqueId); void bulkInsertOpenmrsIds(List<String> ids); Long countUnUsedIds(); UniqueId getNextUniqueId(); int close(String openmrsId); int reserve(String uniqueId); int releaseReservedIds(); int open(String openmrsId); }### Answer: @Test public void testCreateValuesFor() { UniqueId expectedUniqueId = new UniqueId("12", "openrs-id1", "not_used", "test-owner", new Date()); uniqueIdRepository.add(expectedUniqueId); verify(sqLiteDatabase).insert(stringArgumentCaptor.capture(), eq(null), contentValuesArgumentCaptor.capture()); assertEquals("unique_ids", stringArgumentCaptor.getValue()); ContentValues values = contentValuesArgumentCaptor.getValue(); assertEquals("12", values.getAsString("_id")); assertEquals("openrs-id1", values.getAsString("openmrs_id")); assertEquals("not_used", values.getAsString("status")); assertEquals("test-owner", values.getAsString("used_by")); assertNotNull(values.getAsString("created_at")); }
### Question: UniqueIdRepository extends BaseRepository { public int releaseReservedIds() { ContentValues values = new ContentValues(); values.put(STATUS_COLUMN, STATUS_NOT_USED); values.put(USED_BY_COLUMN, ""); values.put(UPDATED_AT_COLUMN, dateFormat.format(new Date())); return getWritableDatabase().update(UniqueIds_TABLE_NAME, values, STATUS_COLUMN + " = ?", new String[]{STATUS_RESERVED}); } static void createTable(SQLiteDatabase database); void add(UniqueId uniqueId); void bulkInsertOpenmrsIds(List<String> ids); Long countUnUsedIds(); UniqueId getNextUniqueId(); int close(String openmrsId); int reserve(String uniqueId); int releaseReservedIds(); int open(String openmrsId); }### Answer: @Test public void testReleaseReserveIds() { uniqueIdRepository.releaseReservedIds(); verify(sqLiteDatabase).update(stringArgumentCaptor.capture(), contentValuesArgumentCaptor.capture(), stringArgumentCaptor.capture(),argsCaptor.capture()); Assert.assertNotNull(stringArgumentCaptor.getValue()); assertEquals("unique_ids", stringArgumentCaptor.getAllValues().get(0)); assertEquals("status = ?", stringArgumentCaptor.getAllValues().get(1)); assertEquals("reserved", argsCaptor.getValue()[0]); ContentValues values = contentValuesArgumentCaptor.getValue(); assertEquals("not_used", values.getAsString("status")); assertEquals("", values.getAsString("used_by")); }
### Question: UniqueIdRepository extends BaseRepository { public int open(String openmrsId) { try { String openmrsId_ = !openmrsId.contains("-") ? formatId(openmrsId) : openmrsId; ContentValues values = new ContentValues(); values.put(STATUS_COLUMN, STATUS_NOT_USED); values.put(USED_BY_COLUMN, ""); values.put(UPDATED_AT_COLUMN, dateFormat.format(new Date())); return updateOpenMRSIdentifierStatus(openmrsId_, values); } catch (Exception e) { Timber.e(e); return 0; } } static void createTable(SQLiteDatabase database); void add(UniqueId uniqueId); void bulkInsertOpenmrsIds(List<String> ids); Long countUnUsedIds(); UniqueId getNextUniqueId(); int close(String openmrsId); int reserve(String uniqueId); int releaseReservedIds(); int open(String openmrsId); }### Answer: @Test public void testOpen() { String openMrsId = "3298938-2"; uniqueIdRepository.open(openMrsId); verify(sqLiteDatabase, times(2)).update(stringArgumentCaptor.capture(), contentValuesArgumentCaptor.capture(), stringArgumentCaptor.capture(), argsCaptor.capture()); Assert.assertNotNull(stringArgumentCaptor.getValue()); assertEquals("unique_ids", stringArgumentCaptor.getAllValues().get(0)); assertEquals("openmrs_id = ?", stringArgumentCaptor.getAllValues().get(1)); assertEquals("32989382", argsCaptor.getValue()[0]); ContentValues values = contentValuesArgumentCaptor.getValue(); assertEquals("not_used", values.getAsString("status")); assertEquals("", values.getAsString("used_by")); }
### Question: P2PSenderTransferDao extends BaseP2PTransferDao implements SenderTransferDao { @Nullable @Override public TreeSet<DataType> getDataTypes() { TreeSet<DataType> dataTypeTreeSet = new TreeSet<>(); if (locationFilterEnabled()) { for (String location : getP2POptions().getLocationsFilter()) { for (DataType dataType : dataTypes) { dataTypeTreeSet.add(new DataType(dataType.getName() + SEPARATOR + location, dataType.getType(), dataTypeTreeSet.size())); } } return dataTypeTreeSet; } else { return new TreeSet<>(dataTypes); } } @Nullable @Override TreeSet<DataType> getDataTypes(); @Nullable @Override JsonData getJsonData(@NonNull DataType dataType, long lastRecordId, int batchSize); @Nullable @Override MultiMediaData getMultiMediaData(@NonNull DataType dataType, long lastRecordId); P2POptions getP2POptions(); }### Answer: @Test public void getDataTypesShouldReturnACloneOfDataType() { TreeSet<DataType> dataTypes = p2PSenderTransferDao.getDataTypes(); Assert.assertEquals(p2PSenderTransferDao.dataTypes.size(), dataTypes.size()); Assert.assertTrue(p2PSenderTransferDao.dataTypes != dataTypes); DataType[] expectedDataTypes = p2PSenderTransferDao.dataTypes.toArray(new DataType[0]); DataType[] actualDataTypes = dataTypes.toArray(new DataType[0]); for (int i = 0; i < expectedDataTypes.length; i++) { Assert.assertEquals(expectedDataTypes[i].getName(), actualDataTypes[i].getName()); Assert.assertEquals(expectedDataTypes[i].getPosition(), actualDataTypes[i].getPosition()); } }
### Question: ClientRelationshipRepository extends BaseRepository { public static void createTable(SQLiteDatabase database) { database.execSQL(CREATE_TABLE); database.execSQL(CREATE_BASE_ENTITY_ID_INDEX); } static void createTable(SQLiteDatabase database); void saveRelationship(ClientRelationship... clientRelationships); List<Client> findClientByRelationship(String relationShip, String relationalId); }### Answer: @Test public void testCreateTableShouldCreateTableAndIndex() { ClientRelationshipRepository.createTable(database); verify(database).execSQL(ClientRelationshipRepository.CREATE_TABLE); verify(database).execSQL(ClientRelationshipRepository.CREATE_BASE_ENTITY_ID_INDEX); }
### Question: ClientRelationshipRepository extends BaseRepository { public List<Client> findClientByRelationship(String relationShip, String relationalId) { List<Client> clientList = new ArrayList<>(); String query = String.format("SELECT %s FROM %s JOIN %s ON %s=%s WHERE %s=? AND %s =?", client_column.json.name(), CLIENT_RELATIONSHIP_TABLE_NAME, client.name(), BASE_ENTITY_ID, client_column.baseEntityId.name(), RELATIONSHIP, RELATIONAL_ID); try (Cursor cursor = getReadableDatabase().rawQuery(query, new String[]{relationShip, relationalId})) { while (cursor.moveToNext()) { clientList.add(JsonFormUtils.gson.fromJson(cursor.getString(0), Client.class)); } } catch (SQLException e) { Timber.e(e); } return clientList; } static void createTable(SQLiteDatabase database); void saveRelationship(ClientRelationship... clientRelationships); List<Client> findClientByRelationship(String relationShip, String relationalId); }### Answer: @Test public void findClientByRelationshipShouldReturnClients() throws JSONException { ClientRelationshipRepository repository = spy(new ClientRelationshipRepository()); when(repository.getReadableDatabase()).thenReturn(database); when(database.rawQuery(anyString(), any())).thenReturn(getClients()); List<Client> clients = repository.findClientByRelationship("family", "12323"); assertEquals(1, clients.size()); assertEquals("03b1321a-d1fb-4fd0-b1cd-a3f3509fc6a6",clients.get(0).getBaseEntityId()); }
### Question: PlanDefinitionRepository extends BaseRepository { public static void createTable(SQLiteDatabase database) { database.execSQL(CREATE_PLAN_DEFINITION_TABLE); } PlanDefinitionRepository(); static void createTable(SQLiteDatabase database); void addOrUpdate(PlanDefinition planDefinition); void deletePlans(@NonNull Set<String> planIdentifiers); PlanDefinition findPlanDefinitionById(String identifier); Set<PlanDefinition> findPlanDefinitionByIds(Set<String> identifiers); Set<PlanDefinition> findAllPlanDefinitions(); Set<String> findAllPlanDefinitionIds(); static Gson gson; }### Answer: @Test public void testCreateTable() { PlanDefinitionRepository.createTable(sqLiteDatabase); verify(sqLiteDatabase).execSQL(stringArgumentCaptor.capture()); assertEquals("CREATE TABLE plan_definition (_id VARCHAR NOT NULL PRIMARY KEY,json VARCHAR NOT NULL,status VARCHAR NOT NULL)", stringArgumentCaptor.getValue()); }
### Question: PlanDefinitionRepository extends BaseRepository { public Set<String> findAllPlanDefinitionIds() { Cursor cursor = null; Set<String> ids = new HashSet<>(); try { String query = String.format("SELECT %s FROM %s WHERE %s =?", ID, PLAN_DEFINITION_TABLE, STATUS); cursor = getReadableDatabase().rawQuery(query, new String[]{ACTIVE.value()}); while (cursor.moveToNext()) { ids.add(cursor.getString(0)); } } catch (Exception e) { Timber.e(e); } finally { if (cursor != null) cursor.close(); } return ids; } PlanDefinitionRepository(); static void createTable(SQLiteDatabase database); void addOrUpdate(PlanDefinition planDefinition); void deletePlans(@NonNull Set<String> planIdentifiers); PlanDefinition findPlanDefinitionById(String identifier); Set<PlanDefinition> findPlanDefinitionByIds(Set<String> identifiers); Set<PlanDefinition> findAllPlanDefinitions(); Set<String> findAllPlanDefinitionIds(); static Gson gson; }### Answer: @Test public void testFindAllPlanDefinitionIds() { when(sqLiteDatabase.rawQuery(anyString(), argsCaptor.capture())) .thenReturn(getIdCursor()); Set<String> planDefinitions = planDefinitionRepository.findAllPlanDefinitionIds(); assertNotNull(planDefinitions); assertEquals(1, planDefinitions.size()); String planDefinition = planDefinitions.iterator().next(); assertEquals("4708ca0a-d0d6-4199-bb1b-8701803c2d02", planDefinition); verify(sqLiteDatabase).rawQuery("SELECT _id FROM plan_definition WHERE status =?", new String[]{ACTIVE.value()}); } @Test public void testFindAllPlanDefinitionIdsWithException() { doThrow(new SQLiteException()).when(sqLiteDatabase).rawQuery(anyString(), any()); Set<String> planDefinitions = planDefinitionRepository.findAllPlanDefinitionIds(); assertTrue(planDefinitions.isEmpty()); verify(sqLiteDatabase).rawQuery("SELECT _id FROM plan_definition WHERE status =?", new String[]{ACTIVE.value()}); }
### Question: UrlUtil { public static boolean isValidUrl(String s){ return new UrlValidator(new String[]{"http", "https"}).isValid(s); } static boolean isValidUrl(String s); }### Answer: @Test public void assertValidUrlPasses() { Assert.assertTrue(UrlUtil.isValidUrl("https: Assert.assertTrue(UrlUtil.isValidUrl("http: } @Test public void assertInValidUrlFails() { Assert.assertFalse(UrlUtil.isValidUrl("invalid.org")); Assert.assertFalse(UrlUtil.isValidUrl("error.test")); }
### Question: SettingsRepository extends DrishtiRepository { @Override protected void onCreate(SQLiteDatabase database) { database.execSQL(SETTINGS_SQL); } static void onUpgrade(SQLiteDatabase database); void updateSetting(String key, String value); void updateSetting(Setting setting); void updateBLOB(String key, byte[] value); String querySetting(String key, String defaultValue); byte[] queryBLOB(String key); Setting querySetting(String key); List<Setting> querySettingsByType(String type); List<Setting> queryUnsyncedSettings(); int queryUnsyncedSettingsCount(); static final String SETTINGS_TABLE_NAME; static final String SETTINGS_KEY_COLUMN; static final String SETTINGS_VALUE_COLUMN; static final String SETTINGS_VERSION_COLUMN; static final String SETTINGS_TYPE_COLUMN; static final String SETTINGS_SYNC_STATUS_COLUMN; static final String SETTINGS_SQL; static final String ADD_SETTINGS_VERSION; static final String ADD_SETTINGS_TYPE; static final String ADD_SETTINGS_SYNC_STATUS; }### Answer: @Test public void assertOnCreate() { settingsRepository.onCreate(sqLiteDatabase); Mockito.verify(sqLiteDatabase, Mockito.times(1)).execSQL(anyString()); }