method2testcases
stringlengths 118
3.08k
|
---|
### Question:
Sequence { public SequenceNumber nextSequenceNumber() { synchronized (lock) { final long tick = updateCounter(); return new SequenceNumber(tick, sequenceToByteArray()); } } Sequence(final SequenceConfig config); SequenceNumber nextSequenceNumber(); }### Answer:
@Test public void nextSequenceNumberShouldIncreaseSequenceNumberLinearly() { final Sequence provider = new Sequence(useDefaults(65536)); final Map<Long, List<SequenceNumber>> groupedByTick = Stream.iterate(0, i -> i + 1) .limit(100) .map(i -> provider.nextSequenceNumber()) .collect(Collectors.groupingBy(SequenceNumber::getTimestamp)); assertFalse(groupedByTick.isEmpty()); for (Long tick : groupedByTick.keySet()) { final List<SequenceNumber> numbers = groupedByTick.get(tick); assertFalse(numbers.isEmpty()); int expectedSequenceNumber = 0; for (SequenceNumber number : numbers) { assertThat(number.getSequenceNumber(), is(toByteArray(expectedSequenceNumber))); expectedSequenceNumber++; } } }
@Test(expected = OutOfSequenceNumbersException.class) public void nextSequenceNumberShouldThrowOutOfSequenceNumbersExceptionIfPoolIsExhausted() { final SequenceConfig config = create(1) .withMaxWaitTime(0, TimeUnit.MILLISECONDS) .build(); final Sequence provider = new Sequence(config); provider.nextSequenceNumber(); provider.nextSequenceNumber(); provider.nextSequenceNumber(); provider.nextSequenceNumber(); }
@Test(expected = BackwardsClockDriftException.class) public void nextSequenceNumberShouldThrowBackwardsClockDriftExceptionIfDriftIsDetected() { final SequenceConfig config = SequenceConfig.create(65536) .withTimeProvider(new DriftingTimeProvider()) .build(); final Sequence provider = new Sequence(config); provider.nextSequenceNumber(); provider.nextSequenceNumber(); } |
### Question:
Flake64L extends Flake64<Long> { @Override public Long nextId() { final SequenceNumber sequenceNumber = getSequence().nextSequenceNumber(); final ByteBuffer bb = (ByteBuffer) toByteBuffer(sequenceNumber); return encoder.encode(bb); } Flake64L(final TimeProvider timeProvider,
final WorkerIdProvider workerIdProvider); Flake64L(final TimeProvider timeProvider,
final WorkerIdProvider workerIdProvider,
final Encoder<ByteBuffer, Long> encoder); @Override Long nextId(); }### Answer:
@Test public void generatedIdsShouldBeLinearlyIncreasingAcrossTimeSlots() { List<Long> generatedIds = new ArrayList<>(); long started = System.nanoTime(); while (System.nanoTime() - started < 200_000_000L) { generatedIds.add(flake.nextId()); } assertFalse(generatedIds.isEmpty()); assertThatListIsStrictlyOrdered(generatedIds); }
@Test public void idsThatHaveBeenGeneratedASecondApartAlsoAreASecondApartInIdSpace() throws InterruptedException { Long id1 = flake.nextId(); Wait.delay(1, TimeUnit.SECONDS); Long id2 = flake.nextId(); long timestampFromId1 = id1 >> 22; long timestampFromId2 = id2 >> 22; long timeBetween = timestampFromId2 - timestampFromId1; assertTrue(timeBetween > 900L && timeBetween < 1_800L); } |
### Question:
AuditMessagePullFilter implements ObjectFilter { @Override public boolean shouldObjectBeSynced(Object object, String action) { AuditMessage auditMessage = (AuditMessage) object; return checkIfEntryAlreadyExists(auditMessage); } @Override boolean shouldObjectBeSynced(Object object, String action); }### Answer:
@Test public void shouldObjectBeSynced_shouldReturnTrueIfEntryAlreadyExists() { boolean fetched = auditMessagePullFilter.shouldObjectBeSynced(prepareDummyAuditMessage( EXISTING_ENTRY_UUID), SAMPLE_ACTION); Assert.assertTrue(fetched); }
@Test public void shouldObjectBeSynced_shouldReturnFalseIfEntryDoesNotExist() { boolean fetched = auditMessagePullFilter.shouldObjectBeSynced(prepareDummyAuditMessage( NEW_ENTRY_UUID2), SAMPLE_ACTION); Assert.assertFalse(fetched); } |
### Question:
AtomfeedEventConfigurationServiceImpl implements EventConfigurationService { @Override public EventConfiguration getEventConfigurationByCategory(SyncCategory categoryEnum) { FeedConfiguration feedConfiguration = feedConfigurationService .getFeedConfigurationByCategory(categoryEnum.getCategory()); return eventConfigurationMapper.map(feedConfiguration); } @Override EventConfiguration getEventConfigurationByCategory(SyncCategory categoryEnum); @Override String extractUuidFromResourceLinks(Map<String, String> eventResourceLinks, String eventCategory,
String preferredClient); }### Answer:
@Test public void getEventConfigurationByCategory_shouldReturnCorrectConfiguration() { EventConfiguration expected = new EventConfiguration(createPatientLinkTemplates()); EventConfiguration actual = atomFeedEventConfigurationService.getEventConfigurationByCategory( new SyncCategory(CategoryEnum.PATIENT.getCategory(), CategoryEnum.PATIENT.getClazz())); Assert.assertNotNull(actual); Assert.assertEquals(expected, actual); } |
### Question:
MergeConflictServiceImpl extends BaseOpenmrsService implements MergeConflictService { @Override public MergeConflict save(MergeConflict mergeConflict) { return mergeConflictDao.save(mergeConflict); } @Override MergeConflict getById(Integer id); @Override MergeConflict getByUuid(String uuid); @Override MergeConflict save(MergeConflict mergeConflict); @Override void delete(MergeConflict mergeConflict, String reason); }### Answer:
@Test public void save_shouldSaveObject() { MergeConflict expected = MergeConflictMother.createInstance(MERGE_CONFLICT_ID); MergeConflict actual = mergeConflictService.save(mergeConflict); Assert.assertEquals(expected, actual); } |
### Question:
MergeConflictServiceImpl extends BaseOpenmrsService implements MergeConflictService { @Override public MergeConflict getById(Integer id) { return mergeConflictDao.getById(id); } @Override MergeConflict getById(Integer id); @Override MergeConflict getByUuid(String uuid); @Override MergeConflict save(MergeConflict mergeConflict); @Override void delete(MergeConflict mergeConflict, String reason); }### Answer:
@Test public void getById_shouldFetchCorrectObject() { MergeConflict expected = MergeConflictMother.createInstance(MERGE_CONFLICT_ID); MergeConflict actual = mergeConflictService.getById(MERGE_CONFLICT_ID); Assert.assertEquals(expected, actual); } |
### Question:
MergeConflictServiceImpl extends BaseOpenmrsService implements MergeConflictService { @Override public MergeConflict getByUuid(String uuid) { return mergeConflictDao.getByUuid(uuid); } @Override MergeConflict getById(Integer id); @Override MergeConflict getByUuid(String uuid); @Override MergeConflict save(MergeConflict mergeConflict); @Override void delete(MergeConflict mergeConflict, String reason); }### Answer:
@Test public void getByUuid_shouldFetchCorrectObject() { MergeConflict expected = MergeConflictMother.createInstance(MERGE_CONFLICT_ID); MergeConflict actual = mergeConflictService.getByUuid(MergeConflictMother.UUID); Assert.assertEquals(expected, actual); } |
### Question:
SyncAuditServiceImpl extends BaseOpenmrsService implements SyncAuditService { @Override public AuditMessage getMessageById(Integer id) throws APIException { return dao.getMessageById(id); } void setDao(SyncAuditDao dao); @Override AuditMessage getMessageByUuid(String uuid); @Override AuditMessage getMessageById(Integer id); @Override String getJsonMessageByUuid(String uuid); @Override String getJsonMessageById(Integer id); @Override String getPaginatedMessages(Integer page, Integer pageSize, Boolean success, String operation,
String resourceName, String creatorInstanceId); @Override AuditMessage saveAuditMessageDuringSync(AuditMessage auditMessage); @Override AuditMessage saveAuditMessage(AuditMessage auditMessage); @Override AuditMessage setNextAudit(AuditMessage current, AuditMessage next); @Override Set<String> getAllCreatorIds(); @Override AuditMessage getMessageByMergeConflictUuid(String uuid); @Override String getJsonMessage(AuditMessage message); }### Answer:
@Test public void getMessageById() throws ParseException { Integer id = 1; AuditMessage expected = prepareAuditMessage(true); when(dao.getMessageById(id)).thenReturn(expected); AuditMessage fetched = auditService.getMessageById(id); Assert.assertEquals(expected, fetched); } |
### Question:
SyncAuditServiceImpl extends BaseOpenmrsService implements SyncAuditService { @Override public AuditMessage getMessageByUuid(String uuid) throws APIException { return dao.getMessageByUuid(uuid); } void setDao(SyncAuditDao dao); @Override AuditMessage getMessageByUuid(String uuid); @Override AuditMessage getMessageById(Integer id); @Override String getJsonMessageByUuid(String uuid); @Override String getJsonMessageById(Integer id); @Override String getPaginatedMessages(Integer page, Integer pageSize, Boolean success, String operation,
String resourceName, String creatorInstanceId); @Override AuditMessage saveAuditMessageDuringSync(AuditMessage auditMessage); @Override AuditMessage saveAuditMessage(AuditMessage auditMessage); @Override AuditMessage setNextAudit(AuditMessage current, AuditMessage next); @Override Set<String> getAllCreatorIds(); @Override AuditMessage getMessageByMergeConflictUuid(String uuid); @Override String getJsonMessage(AuditMessage message); }### Answer:
@Test public void getMessageByUuid() throws ParseException { AuditMessage expected = prepareAuditMessage(true); when(dao.getMessageByUuid(AUDIT_UUID)).thenReturn(expected); AuditMessage fetched = auditService.getMessageByUuid(AUDIT_UUID); Assert.assertEquals(expected, fetched); } |
### Question:
SyncAuditServiceImpl extends BaseOpenmrsService implements SyncAuditService { @Override public String getJsonMessageById(Integer id) throws APIException, JsonParseException { AuditMessage auditMessage = dao.getMessageById(id); if (auditMessage == null) { return null; } else { return serializeResultsWithAuditMessage(auditMessage); } } void setDao(SyncAuditDao dao); @Override AuditMessage getMessageByUuid(String uuid); @Override AuditMessage getMessageById(Integer id); @Override String getJsonMessageByUuid(String uuid); @Override String getJsonMessageById(Integer id); @Override String getPaginatedMessages(Integer page, Integer pageSize, Boolean success, String operation,
String resourceName, String creatorInstanceId); @Override AuditMessage saveAuditMessageDuringSync(AuditMessage auditMessage); @Override AuditMessage saveAuditMessage(AuditMessage auditMessage); @Override AuditMessage setNextAudit(AuditMessage current, AuditMessage next); @Override Set<String> getAllCreatorIds(); @Override AuditMessage getMessageByMergeConflictUuid(String uuid); @Override String getJsonMessage(AuditMessage message); }### Answer:
@Test public void getJsonMessageById() throws Exception { when(dao.getMessageById(AUDIT_ID)).thenReturn(prepareAuditMessage(false)); String expected = readJsonFromFile(AUDIT_MESSAGE_JSON); String fetched = auditService.getJsonMessageById(AUDIT_ID) + System.getProperty("line.separator"); Assert.assertEquals(expected, fetched); } |
### Question:
AuditMessagePushFilter implements ObjectFilter { @Override public boolean shouldObjectBeSynced(Object object, String action) { AuditMessage auditMessage = (AuditMessage) object; return checkIfEntryDoesNotDescribeAuditMessage(auditMessage); } @Override boolean shouldObjectBeSynced(Object object, String action); }### Answer:
@Test public void shouldObjectBeSynced_shouldReturnTrueIfEntryDoesNotDescribeAuditMessage() { boolean fetched = auditMessagePushFilter.shouldObjectBeSynced(prepareDummyAuditMessage( SyncCategoryConstants.CATEGORY_PATIENT), SAMPLE_ACTION); Assert.assertTrue(fetched); }
@Test public void shouldObjectBeSynced_shouldReturnFalseIfEntryDescribesAuditMessage() { boolean fetched = auditMessagePushFilter.shouldObjectBeSynced(prepareDummyAuditMessage( SyncCategoryConstants.CATEGORY_AUDIT_MESSAGE), SAMPLE_ACTION); Assert.assertFalse(fetched); } |
### Question:
SyncAuditServiceImpl extends BaseOpenmrsService implements SyncAuditService { @Override public String getJsonMessageByUuid(String uuid) throws APIException, JsonParseException { AuditMessage auditMessage = dao.getMessageByUuid(uuid); if (auditMessage == null) { return null; } else { return serializeResultsWithAuditMessage(auditMessage); } } void setDao(SyncAuditDao dao); @Override AuditMessage getMessageByUuid(String uuid); @Override AuditMessage getMessageById(Integer id); @Override String getJsonMessageByUuid(String uuid); @Override String getJsonMessageById(Integer id); @Override String getPaginatedMessages(Integer page, Integer pageSize, Boolean success, String operation,
String resourceName, String creatorInstanceId); @Override AuditMessage saveAuditMessageDuringSync(AuditMessage auditMessage); @Override AuditMessage saveAuditMessage(AuditMessage auditMessage); @Override AuditMessage setNextAudit(AuditMessage current, AuditMessage next); @Override Set<String> getAllCreatorIds(); @Override AuditMessage getMessageByMergeConflictUuid(String uuid); @Override String getJsonMessage(AuditMessage message); }### Answer:
@Test public void getJsonMessageByUuid() throws Exception { when(dao.getMessageByUuid(AUDIT_UUID)).thenReturn(prepareAuditMessage(false)); String expected = readJsonFromFile(AUDIT_MESSAGE_JSON); String fetched = auditService.getJsonMessageByUuid(AUDIT_UUID) + System.getProperty("line.separator"); Assert.assertEquals(expected, fetched); } |
### Question:
SyncAuditServiceImpl extends BaseOpenmrsService implements SyncAuditService { @Override public String getPaginatedMessages(Integer page, Integer pageSize, Boolean success, String operation, String resourceName, String creatorInstanceId) throws APIException { PaginatedAuditMessages paginatedAuditMessages = dao.getPaginatedAuditMessages(page, pageSize, success, operation, resourceName, creatorInstanceId); return serializeResultsWithAuditMessage(paginatedAuditMessages); } void setDao(SyncAuditDao dao); @Override AuditMessage getMessageByUuid(String uuid); @Override AuditMessage getMessageById(Integer id); @Override String getJsonMessageByUuid(String uuid); @Override String getJsonMessageById(Integer id); @Override String getPaginatedMessages(Integer page, Integer pageSize, Boolean success, String operation,
String resourceName, String creatorInstanceId); @Override AuditMessage saveAuditMessageDuringSync(AuditMessage auditMessage); @Override AuditMessage saveAuditMessage(AuditMessage auditMessage); @Override AuditMessage setNextAudit(AuditMessage current, AuditMessage next); @Override Set<String> getAllCreatorIds(); @Override AuditMessage getMessageByMergeConflictUuid(String uuid); @Override String getJsonMessage(AuditMessage message); }### Answer:
@Test public void getPaginatedMessages() throws Exception { Integer page = 1; Integer pageSize = 100; PaginatedAuditMessages messages = preparePaginatedAuditMessages(); when(dao.getPaginatedAuditMessages(page, pageSize, null, "", "", "")) .thenReturn(messages); String expected = readJsonFromFile(PAGINATED_AUDIT_MESSAGE_RESPONSE_JSON); String fetched = auditService.getPaginatedMessages( page, pageSize, null, "", "", "") + System.getProperty("line.separator"); Assert.assertEquals(expected, fetched); } |
### Question:
ParentObjectHashcodeServiceImpl extends BaseOpenmrsService implements ParentObjectHashcodeService { @Override public ParentObjectHashcode save(ParentObjectHashcode newParentObjectHashcode) { ParentObjectHashcode parentObjectHashcode = getByObjectUuid(newParentObjectHashcode.getObjectUuid()); if (parentObjectHashcode != null) { parentObjectHashcode.setHashcode(newParentObjectHashcode.getHashcode()); } else { parentObjectHashcode = newParentObjectHashcode; } return parentObjectHashcodeDao.save(parentObjectHashcode); } @Override ParentObjectHashcode getById(Integer id); @Override ParentObjectHashcode getByUuid(String uuid); @Override ParentObjectHashcode getByObjectUuid(String objectUuid); @Override ParentObjectHashcode save(ParentObjectHashcode newParentObjectHashcode); @Override ParentObjectHashcode save(String uuid, String hashCode); @Override void delete(ParentObjectHashcode parentObjectHashcode, String reason); }### Answer:
@Test public void save_shouldSaveObject() { ParentObjectHashcode expected = ParentObjectHashcodeMother.createInstance(OBJECT_ID); ParentObjectHashcode actual = parentObjectHashcodeService.save(parentObjectHashcode); Assert.assertEquals(expected, actual); } |
### Question:
ParentObjectHashcodeServiceImpl extends BaseOpenmrsService implements ParentObjectHashcodeService { @Override public ParentObjectHashcode getById(Integer id) { return parentObjectHashcodeDao.getById(id); } @Override ParentObjectHashcode getById(Integer id); @Override ParentObjectHashcode getByUuid(String uuid); @Override ParentObjectHashcode getByObjectUuid(String objectUuid); @Override ParentObjectHashcode save(ParentObjectHashcode newParentObjectHashcode); @Override ParentObjectHashcode save(String uuid, String hashCode); @Override void delete(ParentObjectHashcode parentObjectHashcode, String reason); }### Answer:
@Test public void getById_shouldFetchCorrectObject() { ParentObjectHashcode expected = ParentObjectHashcodeMother.createInstance(OBJECT_ID); ParentObjectHashcode actual = parentObjectHashcodeService.getById(OBJECT_ID); Assert.assertEquals(expected, actual); } |
### Question:
ParentObjectHashcodeServiceImpl extends BaseOpenmrsService implements ParentObjectHashcodeService { @Override public ParentObjectHashcode getByUuid(String uuid) { return parentObjectHashcodeDao.getByUuid(uuid); } @Override ParentObjectHashcode getById(Integer id); @Override ParentObjectHashcode getByUuid(String uuid); @Override ParentObjectHashcode getByObjectUuid(String objectUuid); @Override ParentObjectHashcode save(ParentObjectHashcode newParentObjectHashcode); @Override ParentObjectHashcode save(String uuid, String hashCode); @Override void delete(ParentObjectHashcode parentObjectHashcode, String reason); }### Answer:
@Test public void getByUuid_shouldFetchCorrectObject() { ParentObjectHashcode expected = ParentObjectHashcodeMother.createInstance(OBJECT_ID); ParentObjectHashcode actual = parentObjectHashcodeService.getByUuid(ParentObjectHashcodeMother.UUID); Assert.assertEquals(expected, actual); } |
### Question:
ParentObjectHashcodeServiceImpl extends BaseOpenmrsService implements ParentObjectHashcodeService { @Override public ParentObjectHashcode getByObjectUuid(String objectUuid) { return parentObjectHashcodeDao.getByObjectUuid(objectUuid); } @Override ParentObjectHashcode getById(Integer id); @Override ParentObjectHashcode getByUuid(String uuid); @Override ParentObjectHashcode getByObjectUuid(String objectUuid); @Override ParentObjectHashcode save(ParentObjectHashcode newParentObjectHashcode); @Override ParentObjectHashcode save(String uuid, String hashCode); @Override void delete(ParentObjectHashcode parentObjectHashcode, String reason); }### Answer:
@Test public void getByObjectUuid_shouldFetchCorrectObject() { ParentObjectHashcode expected = ParentObjectHashcodeMother.createInstance(OBJECT_ID); ParentObjectHashcode actual = parentObjectHashcodeService.getByObjectUuid(ParentObjectHashcodeMother.OBJECT_UUID); Assert.assertEquals(expected, actual); } |
### Question:
AbstractSynchronizationService { protected List<String> determineActions(Object objToUpdate, Object baseObj) { List<String> result = new ArrayList<>(); if (baseObj instanceof BaseOpenmrsData && ((BaseOpenmrsData) baseObj).isVoided()) { result.add(ACTION_VOIDED); } if (objToUpdate == null) { result.add(0, ACTION_CREATED); } else { result.add(0, ACTION_UPDATED); } return result; } }### Answer:
@Test public void determineActions_shouldReturnCREATED() { List<String> actual = abstractSynchronizationService.determineActions( null, createPatientInstance(false)); Assert.assertTrue(actual.contains(SyncConstants.ACTION_CREATED)); }
@Test public void determineActions_shouldReturnUPDATED() { List<String> actual = abstractSynchronizationService.determineActions( createPatientInstance(false), createPatientInstance(false)); Assert.assertTrue(actual.contains(SyncConstants.ACTION_UPDATED)); }
@Test public void determineActions_shouldReturnVOIDED() { List<String> actual = abstractSynchronizationService.determineActions( createPatientInstance(false), createPatientInstance(true)); Assert.assertTrue(actual.contains(SyncConstants.ACTION_VOIDED)); } |
### Question:
AtomfeedEventConfigurationMapperImpl implements EventConfigurationMapper<FeedConfiguration> { @Override public EventConfiguration map(FeedConfiguration feedConfiguration) { return new EventConfiguration(feedConfiguration.getLinkTemplates()); } @Override EventConfiguration map(FeedConfiguration feedConfiguration); }### Answer:
@Test public void map_shouldReturnCorrectEventConfiguration() { EventConfiguration expected = new EventConfiguration(createLinkTemplates()); EventConfiguration actual = eventConfigurationMapper.map(feedConfiguration); Assert.assertNotNull(actual); Assert.assertEquals(expected, actual); } |
### Question:
SimpleObjectSerializationUtils { public static String serialize(SimpleObject simpleObject) { SimpleObjectMessageConverter converter = new SimpleObjectMessageConverter(); return converter.convertToJson(simpleObject); } private SimpleObjectSerializationUtils(); static String serialize(SimpleObject simpleObject); static SimpleObject deserialize(String simpleObject); static SimpleObject clone(SimpleObject simpleObject); }### Answer:
@Test public void serialize_shouldCreateValidJson() { String expected = SyncConfigurationUtils.readResourceFile(EXPECTED_SIMPLE_OBJECT_FILE); SimpleObject simpleObject = SimpleObjectMother.createInstanceWithDateChanged( TEST_DATE_CHANGE, true, false); String actual = SimpleObjectSerializationUtils.serialize(simpleObject); actual += System.getProperty("line.separator"); Assert.assertNotNull(actual); Assert.assertEquals(expected, actual); } |
### Question:
SimpleObjectSerializationUtils { public static SimpleObject deserialize(String simpleObject) { try { return SimpleObject.parseJson(simpleObject); } catch (IOException e) { throw new SerializationException("IOException while deserialize object data", e); } } private SimpleObjectSerializationUtils(); static String serialize(SimpleObject simpleObject); static SimpleObject deserialize(String simpleObject); static SimpleObject clone(SimpleObject simpleObject); }### Answer:
@Test public void deserialize_shouldCreateValidObject() { SimpleObject expected = SimpleObjectMother.createInstanceWithDateChanged( TEST_DATE_CHANGE, true, true); String json = SyncConfigurationUtils.readResourceFile(EXPECTED_SIMPLE_OBJECT_FILE); SimpleObject actual = SimpleObjectSerializationUtils.deserialize(json); Assert.assertNotNull(actual); Assert.assertEquals(expected, actual); } |
### Question:
SimpleObjectSerializationUtils { public static SimpleObject clone(SimpleObject simpleObject) { String stringRepresentation = serialize(simpleObject); return deserialize(stringRepresentation); } private SimpleObjectSerializationUtils(); static String serialize(SimpleObject simpleObject); static SimpleObject deserialize(String simpleObject); static SimpleObject clone(SimpleObject simpleObject); }### Answer:
@Test public void cloneMethod_shouldCorrectlyCloneObject() { SimpleObject expected = SimpleObjectMother.createInstanceWithDateChanged( TEST_DATE_CHANGE, true, true); SimpleObject actual = SimpleObjectSerializationUtils.clone(expected); Assert.assertNotNull(actual); Assert.assertEquals(expected, actual); } |
### Question:
SyncConfigurationUtils { public static String readResourceFile(String file) throws SyncException { try (InputStream in = SyncUtils.class.getClassLoader().getResourceAsStream(file)) { if (in == null) { throw new SyncException("Resource '" + file + "' doesn't exist"); } return IOUtils.toString(in, "UTF-8"); } catch (IOException e) { throw new SyncException(e); } } static void checkIfConfigurationIsValid(); static String readResourceFile(String file); static String readResourceFileAbsolutePath(String file); static SyncConfiguration parseJsonFileToSyncConfiguration(String path, ResourcePathType absolutePath); static SyncConfiguration parseJsonStringToSyncConfiguration(String value); static boolean isValidateJson(String json); static String writeSyncConfigurationToJsonString(SyncConfiguration syncConfiguration); static void writeSyncConfigurationToJsonFile(SyncConfiguration syncConfigurations, String absolutePath); static boolean resourceFileExists(String path); static boolean customConfigExists(String path); static ClientConfiguration getClientConfiguration(String clientName); }### Answer:
@Test public void readResourceFile_shouldReadSampleFile() throws SyncException { final String sampleResourcePath = "sampleTextFile.txt"; final String expectedResult = "sampleContent"; String result = readResourceFile(sampleResourcePath); Assert.assertEquals(result, expectedResult); }
@Test(expected = SyncException.class) public void readResourceFile_shouldThrowIoExceptionIfFileDoesNotExist() throws SyncException { readResourceFile(NOT_EXISTING_FILE_PATH); }
@Test public void serializeMapToPrettyJson_shouldSerializeMapWithStrings() throws SyncException { Assert.assertEquals(readResourceFile(SAMPLE_PRETTY_SERIALIZED_MAP), prettySerialize(createSampleMap())); }
@Test public void serialize_shouldSerializeMapToJson() throws SyncException { Assert.assertEquals(readResourceFile(SAMPLE_SERIALIZED_MAP), serialize(createSampleMap())); }
@Test public void deserializeJsonToStringsMap_shouldDeserializeMapWithStrings() throws SyncException { Assert.assertEquals(createSampleMap(), SyncUtils.deserializeJsonToStringsMap(readResourceFile(SAMPLE_SERIALIZED_MAP))); } |
### Question:
SyncConfigurationUtils { public static SyncConfiguration parseJsonFileToSyncConfiguration(String path, ResourcePathType absolutePath) { ObjectMapper mapper = new ObjectMapper(); try { String resourceFile = absolutePath.equals(ABSOLUTE) ? readResourceFileAbsolutePath(path) : readResourceFile(path); return mapper.readValue(resourceFile, SyncConfiguration.class); } catch (IOException e) { throw new SyncException(e); } } static void checkIfConfigurationIsValid(); static String readResourceFile(String file); static String readResourceFileAbsolutePath(String file); static SyncConfiguration parseJsonFileToSyncConfiguration(String path, ResourcePathType absolutePath); static SyncConfiguration parseJsonStringToSyncConfiguration(String value); static boolean isValidateJson(String json); static String writeSyncConfigurationToJsonString(SyncConfiguration syncConfiguration); static void writeSyncConfigurationToJsonFile(SyncConfiguration syncConfigurations, String absolutePath); static boolean resourceFileExists(String path); static boolean customConfigExists(String path); static ClientConfiguration getClientConfiguration(String clientName); }### Answer:
@Test public void parseJsonFileToSyncConfiguration_shouldCorrectlyParseSampleConfiguration() throws SyncException { SyncConfiguration result = parseJsonFileToSyncConfiguration(SAMPLE_SYNC_CONFIGURATION_PATH, RELATIVE); Assert.assertEquals(EXPECTED_CONFIGURATION, result); }
@Test(expected = SyncException.class) public void parseJsonFileToSyncConfiguration_shouldThrowJsonParseException() throws SyncException { parseJsonFileToSyncConfiguration(INCORRECT_SYNC_CONFIGURATION_PATH, RELATIVE); } |
### Question:
SyncConfigurationUtils { public static boolean resourceFileExists(String path) { InputStream in = SyncUtils.class.getClassLoader().getResourceAsStream(path); return in != null; } static void checkIfConfigurationIsValid(); static String readResourceFile(String file); static String readResourceFileAbsolutePath(String file); static SyncConfiguration parseJsonFileToSyncConfiguration(String path, ResourcePathType absolutePath); static SyncConfiguration parseJsonStringToSyncConfiguration(String value); static boolean isValidateJson(String json); static String writeSyncConfigurationToJsonString(SyncConfiguration syncConfiguration); static void writeSyncConfigurationToJsonFile(SyncConfiguration syncConfigurations, String absolutePath); static boolean resourceFileExists(String path); static boolean customConfigExists(String path); static ClientConfiguration getClientConfiguration(String clientName); }### Answer:
@Test public void resourceFileExists_exist() throws SyncException { Assert.assertTrue(resourceFileExists(SAMPLE_SYNC_CONFIGURATION_PATH)); }
@Test public void resourceFileExists_notExist() throws SyncException { Assert.assertFalse(resourceFileExists(NOT_EXISTING_FILE_PATH)); } |
### Question:
SyncClient { public Object pullData(SyncCategory category, String clientName, String resourceUrl, OpenMRSSyncInstance instance) { Object result = null; setUpCredentials(clientName, instance); ClientHelper clientHelper = ClientHelperFactory.createClient(clientName); prepareRestTemplate(clientHelper); String destinationUrl = getDestinationUri(instance, clientName); try { result = retrieveObject(category, resourceUrl, destinationUrl, clientName, instance); } catch (HttpClientErrorException e) { if (e.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) { throw new SyncException("Unauthorized error during reading parent object: ", e); } if (!e.getStatusCode().equals(HttpStatus.NOT_FOUND)) { throw new SyncException("Error during reading local object: ", e); } } catch (URISyntaxException e) { LOGGER.error(e.getMessage()); } return result; } Object pullData(SyncCategory category, String clientName, String resourceUrl, OpenMRSSyncInstance instance); ResponseEntity<String> pushData(SyncCategory category, Object object, String clientName,
String resourceUrl, String action, OpenMRSSyncInstance instance); }### Answer:
@Test public void pullDataFromParent_shouldCallRestClient() { SyncClient resourceManager = new SyncClient(); Object pulledObject = resourceManager.pullData(PATIENT_CATEGORY, REST_CLIENT_KEY, REST_FULL_RESOURCE_URL, PARENT); assertThat((Patient) pulledObject, is(expectedPatient)); }
@Test public void pullDataFromParent_shouldCallFHIRClient() { SyncClient resourceManager = new SyncClient(); Object pulledObject = resourceManager.pullData(PATIENT_CATEGORY, FHIR_CLIENT_KEY, FHIR_FULL_RESOURCE_URL, PARENT); assertThat((Patient) pulledObject, is(expectedPatient)); } |
### Question:
RESTClientHelper implements ClientHelper { @Override public ClientHttpEntity retrieveRequest(String url) throws URISyntaxException { return new ClientHttpEntity(HttpMethod.GET, new URI(url)); } @Override ClientHttpEntity retrieveRequest(String url); @Override ClientHttpEntity createRequest(String url, Object object); @Override ClientHttpEntity deleteRequest(String url, String uuid); @Override ClientHttpEntity updateRequest(String url, Object object); @Override Class resolveClassByCategory(String category); @Override List<ClientHttpRequestInterceptor> getCustomInterceptors(String username, String password); @Override List<HttpMessageConverter<?>> getCustomMessageConverter(); @Override boolean compareResourceObjects(String category, Object from, Object dest); @Override Object convertToObject(String formattedData, Class<?> clazz); @Override String convertToFormattedData(Object object); @Override Object convertToOpenMrsObject(Object o, String category); }### Answer:
@Test public void retrieveRequest() throws Exception { ClientHttpEntity expected = new ClientHttpEntity(HttpMethod.GET, URI.create(TEST_URI)); RESTClientHelper restClientHelper = new RESTClientHelper(); assertEquals(expected, restClientHelper.retrieveRequest(TEST_URI)); } |
### Question:
RESTClientHelper implements ClientHelper { @Override public ClientHttpEntity createRequest(String url, Object object) throws URISyntaxException { if (object instanceof SimpleObject) { getRestResourceConverter().convertObject(url, object); } return new ClientHttpEntity<String>(convertToFormattedData(object), HttpMethod.POST, new URI(url)); } @Override ClientHttpEntity retrieveRequest(String url); @Override ClientHttpEntity createRequest(String url, Object object); @Override ClientHttpEntity deleteRequest(String url, String uuid); @Override ClientHttpEntity updateRequest(String url, Object object); @Override Class resolveClassByCategory(String category); @Override List<ClientHttpRequestInterceptor> getCustomInterceptors(String username, String password); @Override List<HttpMessageConverter<?>> getCustomMessageConverter(); @Override boolean compareResourceObjects(String category, Object from, Object dest); @Override Object convertToObject(String formattedData, Class<?> clazz); @Override String convertToFormattedData(Object object); @Override Object convertToOpenMrsObject(Object o, String category); }### Answer:
@Test public void createRequest() throws Exception { Patient patient = new Patient(); SimpleObject simpleObject = getSimpleObject(patient); String json = (new SimpleObjectMessageConverter()).convertToJson(simpleObject); ClientHttpEntity expected = new ClientHttpEntity<String>(json, HttpMethod.POST, URI.create(TEST_URI)); assertEquals(expected, restClientHelper.createRequest(TEST_URI, simpleObject)); } |
### Question:
RESTClientHelper implements ClientHelper { @Override public ClientHttpEntity deleteRequest(String url, String uuid) throws URISyntaxException { url += "/" + uuid; return new ClientHttpEntity<String>(uuid, HttpMethod.DELETE, new URI(url)); } @Override ClientHttpEntity retrieveRequest(String url); @Override ClientHttpEntity createRequest(String url, Object object); @Override ClientHttpEntity deleteRequest(String url, String uuid); @Override ClientHttpEntity updateRequest(String url, Object object); @Override Class resolveClassByCategory(String category); @Override List<ClientHttpRequestInterceptor> getCustomInterceptors(String username, String password); @Override List<HttpMessageConverter<?>> getCustomMessageConverter(); @Override boolean compareResourceObjects(String category, Object from, Object dest); @Override Object convertToObject(String formattedData, Class<?> clazz); @Override String convertToFormattedData(Object object); @Override Object convertToOpenMrsObject(Object o, String category); }### Answer:
@Test public void deleteRequest() throws Exception { ClientHttpEntity expected = new ClientHttpEntity<String>(TEST_PATIENT_UUID, HttpMethod.DELETE, URI.create(TEST_URI + "/" + TEST_PATIENT_UUID)); RESTClientHelper restClientHelper = new RESTClientHelper(); assertEquals(expected, restClientHelper.deleteRequest(TEST_URI, TEST_PATIENT_UUID)); } |
### Question:
RESTClientHelper implements ClientHelper { @Override public ClientHttpEntity updateRequest(String url, Object object) throws URISyntaxException { if (object instanceof AuditMessage) { url += "/" + ((AuditMessage) object).getUuid(); return new ClientHttpEntity<String>(convertToFormattedData(object), HttpMethod.POST, new URI(url)); } else { getRestResourceConverter().convertObject(url, object); url += "/" + ((SimpleObject) object).get("uuid"); } return new ClientHttpEntity<String>(convertToFormattedData(object), HttpMethod.POST, new URI(url)); } @Override ClientHttpEntity retrieveRequest(String url); @Override ClientHttpEntity createRequest(String url, Object object); @Override ClientHttpEntity deleteRequest(String url, String uuid); @Override ClientHttpEntity updateRequest(String url, Object object); @Override Class resolveClassByCategory(String category); @Override List<ClientHttpRequestInterceptor> getCustomInterceptors(String username, String password); @Override List<HttpMessageConverter<?>> getCustomMessageConverter(); @Override boolean compareResourceObjects(String category, Object from, Object dest); @Override Object convertToObject(String formattedData, Class<?> clazz); @Override String convertToFormattedData(Object object); @Override Object convertToOpenMrsObject(Object o, String category); }### Answer:
@Test public void updateRequest() throws Exception { Patient patient = new Patient(); patient.setUuid(TEST_PATIENT_UUID); SimpleObject simpleObject = getSimpleObject(patient); String json = (new SimpleObjectMessageConverter()).convertToJson(simpleObject); ClientHttpEntity expected = new ClientHttpEntity<String>(json, HttpMethod.POST, URI.create(TEST_URI + "/" + TEST_PATIENT_UUID)); assertEquals(expected, restClientHelper.updateRequest(TEST_URI, simpleObject)); } |
### Question:
RESTClientHelper implements ClientHelper { @Override public Class resolveClassByCategory(String category) { if (category.equalsIgnoreCase(CATEGORY_AUDIT_MESSAGE)) { return AuditMessage.class; } return SimpleObject.class; } @Override ClientHttpEntity retrieveRequest(String url); @Override ClientHttpEntity createRequest(String url, Object object); @Override ClientHttpEntity deleteRequest(String url, String uuid); @Override ClientHttpEntity updateRequest(String url, Object object); @Override Class resolveClassByCategory(String category); @Override List<ClientHttpRequestInterceptor> getCustomInterceptors(String username, String password); @Override List<HttpMessageConverter<?>> getCustomMessageConverter(); @Override boolean compareResourceObjects(String category, Object from, Object dest); @Override Object convertToObject(String formattedData, Class<?> clazz); @Override String convertToFormattedData(Object object); @Override Object convertToOpenMrsObject(Object o, String category); }### Answer:
@Test public void resolveClassByCategory() { RESTClientHelper restClientHelper = new RESTClientHelper(); assertEquals(SimpleObject.class, restClientHelper.resolveClassByCategory(CATEGORY_PATIENT)); assertEquals(SimpleObject.class, restClientHelper.resolveClassByCategory(CATEGORY_VISIT)); assertEquals(AuditMessage.class, restClientHelper.resolveClassByCategory(CATEGORY_AUDIT_MESSAGE)); } |
### Question:
LazyCachingSupplier implements Supplier<T> { public static <T> LazyCachingSupplier<T> lazyCaching(Supplier<T> supplier) { return new LazyCachingSupplier<>(supplier); } private LazyCachingSupplier(Supplier<T> supplier); @Override T get(); static LazyCachingSupplier<T> lazyCaching(Supplier<T> supplier); }### Answer:
@Test public void testSuppliersGetIsNotCalledOnInitialization() { LazyCachingSupplier.lazyCaching(() -> { fail("Should never be called"); return "never"; }); } |
### Question:
MessageListCollector { public static Collector<Message, ?, MessageList> toMessageList() { return Collector.of(MessageList::new, MessageList::add, addAll()); } private MessageListCollector(); static Collector<Message, ?, MessageList> toMessageList(); }### Answer:
@Test public void testToMessageList_Parallel() { MessageList sortedMessageList = Stream.of(Message.newInfo("A", "bla"), Message.newError("B", "blubb")) .parallel() .collect(MessageListCollector.toMessageList()); assertThat(sortedMessageList, hasSize(2)); assertThat(sortedMessageList, hasInfoMessage("A")); assertThat(sortedMessageList, hasErrorMessage("B")); List<String> codes = sortedMessageList.stream().map(Message::getCode).collect(toList()); assertThat(codes, contains("A", "B")); }
@Test public void testToMessageList() { MessageList emptyMessageList = Stream.<Message> empty().collect(toMessageList()); assertThat(emptyMessageList, is(emptyMessageList())); MessageList singleMessageList = Stream.of(Message.newError("A", "bla")) .collect(MessageListCollector.toMessageList()); assertThat(singleMessageList, hasSize(1)); MessageList sortedMessageList = Stream.of(Message.newInfo("A", "bla"), Message.newError("B", "blubb")) .collect(MessageListCollector.toMessageList()); assertThat(sortedMessageList, hasSize(2)); assertThat(sortedMessageList, hasInfoMessage("A")); assertThat(sortedMessageList, hasErrorMessage("B")); List<String> codes = sortedMessageList.stream().map(Message::getCode).collect(toList()); assertThat(codes, contains("A", "B")); } |
### Question:
ObjectProperty implements Serializable { @Override public int hashCode() { return hashCode; } ObjectProperty(Object object, @CheckForNull String property, int index); ObjectProperty(Object object, String property); ObjectProperty(Object object); Object getObject(); @CheckForNull String getProperty(); int getIndex(); boolean hasIndex(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testHashCode() { ObjectProperty objectProperty = new ObjectProperty("foo"); assertThat(objectProperty.hashCode(), is(objectProperty.hashCode())); assertThat(new ObjectProperty("foo").hashCode(), is(new ObjectProperty("foo").hashCode())); assertThat(new ObjectProperty("foo", "bar").hashCode(), is(new ObjectProperty("foo", "bar").hashCode())); assertThat(new ObjectProperty("foo", "bar", 1).hashCode(), is(new ObjectProperty("foo", "bar", 1).hashCode())); }
@Test public void testHashCode_IsCached() { HashCodeCounter hashCodeCounter = new HashCodeCounter(); ObjectProperty objectProperty = new ObjectProperty(hashCodeCounter); assertThat(objectProperty.hashCode(), is(objectProperty.hashCode())); assertThat(hashCodeCounter.count, is(1)); } |
### Question:
ObjectProperty implements Serializable { public boolean hasIndex() { return index >= 0; } ObjectProperty(Object object, @CheckForNull String property, int index); ObjectProperty(Object object, String property); ObjectProperty(Object object); Object getObject(); @CheckForNull String getProperty(); int getIndex(); boolean hasIndex(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testHasIndex() { String object = "foo"; assertThat(new ObjectProperty(object).hasIndex(), is(false)); assertThat(new ObjectProperty(object, "chars").hasIndex(), is(false)); assertThat(new ObjectProperty(object, "chars", 1).hasIndex(), is(true)); } |
### Question:
MessageList implements Serializable, Iterable<Message> { public MessageList getMessagesByMarker(@CheckForNull ValidationMarker marker) { return messages.stream() .filter(m -> (marker == null && !m.hasMarkers()) || marker != null && m.hasMarker(marker)) .collect(toMessageList()); } MessageList(@NonNull Message... messages); void add(Message message); void add(@CheckForNull MessageList messageList); boolean isEmpty(); int size(); Message getMessage(int index); Optional<Message> getFirstMessage(Severity errorLevel); Optional<Message> getMessageByCode(@CheckForNull String code); MessageList getMessagesByCode(@CheckForNull String code); Optional<Severity> getSeverity(); String getText(); boolean containsErrorMsg(); MessageList getMessagesFor(Object object); MessageList getMessagesFor(Object object, @CheckForNull String property); MessageList getMessagesFor(Object object, @CheckForNull String property, int index); MessageList getMessagesByMarker(@CheckForNull ValidationMarker marker); MessageList getMessagesByMarker(Predicate<ValidationMarker> markerPredicate); MessageList sortBySeverity(); Optional<Message> getMessageWithHighestSeverity(); @Override Iterator<Message> iterator(); void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Stream<Message> stream(); static Collector<Message, ?, MessageList> collector(); }### Answer:
@SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testGetMessagesByMarker_predicateNull_shouldThrowNullPointerException() { Assertions.assertThrows(NullPointerException.class, () -> { new MessageList().getMessagesByMarker((Predicate)null); }); } |
### Question:
MessageList implements Serializable, Iterable<Message> { public Optional<Message> getMessageWithHighestSeverity() { return messages.stream() .sorted(Comparator.comparing(Message::getSeverity).reversed()) .findFirst(); } MessageList(@NonNull Message... messages); void add(Message message); void add(@CheckForNull MessageList messageList); boolean isEmpty(); int size(); Message getMessage(int index); Optional<Message> getFirstMessage(Severity errorLevel); Optional<Message> getMessageByCode(@CheckForNull String code); MessageList getMessagesByCode(@CheckForNull String code); Optional<Severity> getSeverity(); String getText(); boolean containsErrorMsg(); MessageList getMessagesFor(Object object); MessageList getMessagesFor(Object object, @CheckForNull String property); MessageList getMessagesFor(Object object, @CheckForNull String property, int index); MessageList getMessagesByMarker(@CheckForNull ValidationMarker marker); MessageList getMessagesByMarker(Predicate<ValidationMarker> markerPredicate); MessageList sortBySeverity(); Optional<Message> getMessageWithHighestSeverity(); @Override Iterator<Message> iterator(); void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Stream<Message> stream(); static Collector<Message, ?, MessageList> collector(); }### Answer:
@Test public void testGetMessageWithHighestSeverity() { MessageList messages = new MessageList(Message.builder("info", Severity.INFO).create(), Message.builder("error", Severity.ERROR).create(), Message.builder("warning", Severity.WARNING).create()); Optional<Message> message = messages.getMessageWithHighestSeverity(); assertThat(message, is(present())); assertThat(message.get().getSeverity(), is(Severity.ERROR)); }
@Test public void testGetMessageWithHighestSeverity_null() { MessageList messages = new MessageList(); Optional<Message> message = messages.getMessageWithHighestSeverity(); assertThat(message, is(not(present()))); } |
### Question:
MessageList implements Serializable, Iterable<Message> { public String getText() { return messages.stream() .map(Message::getText) .collect(Collectors.joining("\n")); } MessageList(@NonNull Message... messages); void add(Message message); void add(@CheckForNull MessageList messageList); boolean isEmpty(); int size(); Message getMessage(int index); Optional<Message> getFirstMessage(Severity errorLevel); Optional<Message> getMessageByCode(@CheckForNull String code); MessageList getMessagesByCode(@CheckForNull String code); Optional<Severity> getSeverity(); String getText(); boolean containsErrorMsg(); MessageList getMessagesFor(Object object); MessageList getMessagesFor(Object object, @CheckForNull String property); MessageList getMessagesFor(Object object, @CheckForNull String property, int index); MessageList getMessagesByMarker(@CheckForNull ValidationMarker marker); MessageList getMessagesByMarker(Predicate<ValidationMarker> markerPredicate); MessageList sortBySeverity(); Optional<Message> getMessageWithHighestSeverity(); @Override Iterator<Message> iterator(); void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Stream<Message> stream(); static Collector<Message, ?, MessageList> collector(); }### Answer:
@Test public void testGetText() { MessageList messageList = new MessageList(Message.newInfo("don't care", "we care"), Message.newError("don't care", "even more")); assertThat(messageList.getText(), is("we care\neven more")); }
@Test public void testGetText_OneMessageList() { MessageList messageList = new MessageList(Message.newInfo("don't care", "we care")); assertThat(messageList.getText(), is("we care")); }
@Test public void testGetText_emptyList_shouldReturnEmptyString() { MessageList emptyMessageList = new MessageList(); assertThat(emptyMessageList.getText(), is(StringUtils.EMPTY)); } |
### Question:
MessageList implements Serializable, Iterable<Message> { public MessageList getMessagesFor(Object object) { return getMessagesFor(object, null); } MessageList(@NonNull Message... messages); void add(Message message); void add(@CheckForNull MessageList messageList); boolean isEmpty(); int size(); Message getMessage(int index); Optional<Message> getFirstMessage(Severity errorLevel); Optional<Message> getMessageByCode(@CheckForNull String code); MessageList getMessagesByCode(@CheckForNull String code); Optional<Severity> getSeverity(); String getText(); boolean containsErrorMsg(); MessageList getMessagesFor(Object object); MessageList getMessagesFor(Object object, @CheckForNull String property); MessageList getMessagesFor(Object object, @CheckForNull String property, int index); MessageList getMessagesByMarker(@CheckForNull ValidationMarker marker); MessageList getMessagesByMarker(Predicate<ValidationMarker> markerPredicate); MessageList sortBySeverity(); Optional<Message> getMessageWithHighestSeverity(); @Override Iterator<Message> iterator(); void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Stream<Message> stream(); static Collector<Message, ?, MessageList> collector(); }### Answer:
@Test public void testGetMessagesFor_noObjects_shouldReturnEmptyMessageList() { MessageList messages = new MessageList(Message.newError("code", "msg"), Message.newWarning("code", "msg")) .getMessagesFor(new Object()); assertThat(messages, is(emptyMessageList())); }
@Test public void testGetMessagesFor_objectNull_shouldThrowNullPointerException() { Assertions.assertThrows(NullPointerException.class, () -> { new MessageList(Message.newError("code", "msg"), Message.newWarning("code", "msg")) .getMessagesFor(null); }); } |
### Question:
MessageList implements Serializable, Iterable<Message> { public Optional<Severity> getSeverity() { return messages.stream() .map(Message::getSeverity) .max(Comparator.comparing(Severity::ordinal)); } MessageList(@NonNull Message... messages); void add(Message message); void add(@CheckForNull MessageList messageList); boolean isEmpty(); int size(); Message getMessage(int index); Optional<Message> getFirstMessage(Severity errorLevel); Optional<Message> getMessageByCode(@CheckForNull String code); MessageList getMessagesByCode(@CheckForNull String code); Optional<Severity> getSeverity(); String getText(); boolean containsErrorMsg(); MessageList getMessagesFor(Object object); MessageList getMessagesFor(Object object, @CheckForNull String property); MessageList getMessagesFor(Object object, @CheckForNull String property, int index); MessageList getMessagesByMarker(@CheckForNull ValidationMarker marker); MessageList getMessagesByMarker(Predicate<ValidationMarker> markerPredicate); MessageList sortBySeverity(); Optional<Message> getMessageWithHighestSeverity(); @Override Iterator<Message> iterator(); void clear(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Stream<Message> stream(); static Collector<Message, ?, MessageList> collector(); }### Answer:
@Test public void testGetSeverity() { MessageList messageList = new MessageList( Message.newInfo(ANY, ANY), Message.newError(ANY, ANY), Message.newWarning(ANY, ANY)); assertThat(messageList.getSeverity(), is(hasValue(Severity.ERROR))); }
@Test public void testGetSeverity_OneSeverity() { MessageList messageList = new MessageList( Message.newInfo(ANY, ANY), Message.newInfo(ANY, ANY)); assertThat(messageList.getSeverity(), is(hasValue(Severity.INFO))); }
@Test public void testGetSeverity_EmptyList() { assertThat(new MessageList().getSeverity(), is(absent())); } |
### Question:
Message implements Serializable { public static Builder builder(String text, Severity severity) { Objects.requireNonNull(text, "text must not be null"); Objects.requireNonNull(severity, "severity must not be null"); return new Builder(text, severity); } Message(@CheckForNull String code, String text, Severity severity); Message(@CheckForNull String code, String text, Severity severity,
@CheckForNull List<ObjectProperty> invalidObjectProperties, @CheckForNull Set<ValidationMarker> markers); static Message newInfo(String code, String text); static Message newWarning(String code, String text); static Message newError(String code, String text); Severity getSeverity(); String getText(); @CheckForNull String getCode(); List<ObjectProperty> getInvalidObjectProperties(); Set<ValidationMarker> getMarkers(); boolean hasMarker(ValidationMarker marker); boolean hasMarkers(); boolean isMandatoryFieldMessage(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Builder builder(String text, Severity severity); }### Answer:
@Test public void testEquals_NotEqual_ObjectProperties() { Object invalidObject = new Object(); ObjectProperty objectProperty = new ObjectProperty(invalidObject); ValidationMarker validationMarker = () -> false; Message message1 = Message.builder("text", Severity.INFO).code("code").markers(validationMarker) .invalidObjectWithProperties(invalidObject).create(); Message message2 = Message.builder("text", Severity.INFO).code("code").markers(validationMarker) .invalidObjects(objectProperty, objectProperty).create(); Message message3 = Message.builder("text", Severity.INFO).code("code").markers(validationMarker) .invalidObjectWithProperties(invalidObject, "foo", "bar").create(); assertThat(message1, is(not(equalTo(message2)))); assertThat(message1, is(not(equalTo(message3)))); } |
### Question:
Message implements Serializable { @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(severity.toString()) .append(' ') .append(code) .append('['); int max = invalidProperties.size(); for (int i = 0; i < max; i++) { if (i > 0) { buffer.append(", "); } buffer.append(invalidProperties.get(i).getObject().toString()) .append('.') .append(invalidProperties.get(i).getProperty()); } buffer.append(']') .append('\n') .append(text); return buffer.toString(); } Message(@CheckForNull String code, String text, Severity severity); Message(@CheckForNull String code, String text, Severity severity,
@CheckForNull List<ObjectProperty> invalidObjectProperties, @CheckForNull Set<ValidationMarker> markers); static Message newInfo(String code, String text); static Message newWarning(String code, String text); static Message newError(String code, String text); Severity getSeverity(); String getText(); @CheckForNull String getCode(); List<ObjectProperty> getInvalidObjectProperties(); Set<ValidationMarker> getMarkers(); boolean hasMarker(ValidationMarker marker); boolean hasMarkers(); boolean isMandatoryFieldMessage(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Builder builder(String text, Severity severity); }### Answer:
@Test public void testToString() { Message message = new Message("code", "text", Severity.WARNING, Arrays.asList(new ObjectProperty("Object", "property", 1)), Collections.singleton(() -> true)); assertThat(message.toString(), is("WARNING code[Object.property]\ntext")); } |
### Question:
Message implements Serializable { public boolean isMandatoryFieldMessage() { return getMarkers() .stream() .anyMatch(ValidationMarker::isRequiredInformationMissing); } Message(@CheckForNull String code, String text, Severity severity); Message(@CheckForNull String code, String text, Severity severity,
@CheckForNull List<ObjectProperty> invalidObjectProperties, @CheckForNull Set<ValidationMarker> markers); static Message newInfo(String code, String text); static Message newWarning(String code, String text); static Message newError(String code, String text); Severity getSeverity(); String getText(); @CheckForNull String getCode(); List<ObjectProperty> getInvalidObjectProperties(); Set<ValidationMarker> getMarkers(); boolean hasMarker(ValidationMarker marker); boolean hasMarkers(); boolean isMandatoryFieldMessage(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Builder builder(String text, Severity severity); }### Answer:
@Test public void testIsMandatoryFieldMessage() { ValidationMarker mandatoryMarker = () -> true; ValidationMarker notMandatoryMarker = () -> false; assertThat(createMessage().isMandatoryFieldMessage(), is(false)); assertThat(createMessage(notMandatoryMarker).isMandatoryFieldMessage(), is(false)); assertThat(createMessage(mandatoryMarker).isMandatoryFieldMessage(), is(true)); assertThat(createMessage(notMandatoryMarker, mandatoryMarker).isMandatoryFieldMessage(), is(true)); } |
### Question:
BindingManager { public void removeUiUpdateObserver(UiUpdateObserver observer) { requireNonNull(observer, "observer must not be null"); uiUpdateObservers.remove(observer); } BindingManager(ValidationService validationService); @Deprecated BindingContext startNewContext(Class<?> clazz); BindingContext createContext(Class<?> clazz, PropertyBehaviorProvider behaviorProvider); @Deprecated BindingContext startNewContext(String name); BindingContext createContext(String name, PropertyBehaviorProvider behaviorProvider); BindingContext getContext(Class<?> clazz); BindingContext getContext(String name); @Deprecated Optional<BindingContext> getExistingContext(Class<?> clazz); @Deprecated Optional<BindingContext> getExistingContext(String name); @Deprecated BindingContext getExistingContextOrStartNewOne(Class<?> clazz); @Deprecated BindingContext getExistingContextOrStartNewOne(String name); void removeContext(BindingContext context); void removeAllContexts(); void addUiUpdateObserver(UiUpdateObserver observer); void removeUiUpdateObserver(UiUpdateObserver observer); void afterUpdateUi(); void notifyUiUpdateObservers(); @Override String toString(); }### Answer:
@Test public void testRemoveUiUpdateObserver() { TestBindingManager bindingManager = new TestBindingManager(() -> new MessageList()); UiUpdateObserver observer = mock(UiUpdateObserver.class); bindingManager.addUiUpdateObserver(observer); bindingManager.removeUiUpdateObserver(observer); bindingManager.afterUpdateUi(); verify(observer, never()).uiUpdated(); } |
### Question:
ContainerBinding extends BindingContext implements Binding { @Override public void modelChanged() { modelChanged.apply(); } ContainerBinding(Binding selfBinding, PropertyBehaviorProvider behaviorProvider,
PropertyDispatcherFactory dispatcherFactory, Handler modelChanged); @Override void modelChanged(); @Override void updateFromPmo(); @Override Object getBoundComponent(); @Override Object getPmo(); }### Answer:
@Test public void testModelChanged_IsForwardedToParent() { BindingContext bindingContext = spy(new BindingContext()); ComponentWrapper componentWrapper = new TestComponentWrapper(new TestUiComponent()); ContainerBinding binding = bindingContext.bindContainer(new TestPmo(new TestModelObject()), BoundProperty.of("test"), Arrays.asList(), componentWrapper); binding.modelChanged(); verify(bindingContext).modelChanged(); }
@Test public void testModelChanged() { BindingContext bindingContext = new BindingContext(); ComponentWrapper componentWrapper = new TestComponentWrapper(new TestUiComponent()); TestAspectDef testAspectDef = new TestAspectDef(); ContainerBinding binding = bindingContext.bindContainer(new Object(), BoundProperty.of("test"), Arrays.asList(testAspectDef), componentWrapper); testAspectDef.triggered = false; binding.modelChanged(); assertThat(testAspectDef.triggered, is(true)); } |
### Question:
ContainerBinding extends BindingContext implements Binding { @Override public void updateFromPmo() { binding.updateFromPmo(); super.updateFromPmo(); } ContainerBinding(Binding selfBinding, PropertyBehaviorProvider behaviorProvider,
PropertyDispatcherFactory dispatcherFactory, Handler modelChanged); @Override void modelChanged(); @Override void updateFromPmo(); @Override Object getBoundComponent(); @Override Object getPmo(); }### Answer:
@Test public void testUpdateFromPmo_ManuallyUpdated() { BindingContext bindingContext = new BindingContext(); ComponentWrapper componentWrapper = new TestComponentWrapper(new TestUiComponent()); TestAspectDef testAspectDef = new TestAspectDef(); bindingContext.bindContainer(new TestPmo(new TestModelObject()), BoundProperty.of("test"), Arrays.asList(testAspectDef), componentWrapper); testAspectDef.triggered = false; bindingContext.updateFromPmo(); assertThat(testAspectDef.triggered, is(true)); }
@Test public void testUpdateFromPmo_ContainerBindingBeforeChildren() { BindingContext bindingContext = new BindingContext(); ComponentWrapper componentWrapper = new TestComponentWrapper(new TestUiComponent()); TestAspectDef testAspectDef = new TestAspectDef(); TestDependantAspectDef testDependantAspectDef = new TestDependantAspectDef(testAspectDef); ContainerBinding binding = bindingContext.bindContainer(new Object(), BoundProperty.of("test"), Arrays.asList(testAspectDef), componentWrapper); binding.bind(new Object(), BoundProperty.of("test2"), Arrays.asList(testDependantAspectDef), componentWrapper); assertThat(testAspectDef.triggered, is(true)); assertThat(testDependantAspectDef.triggered, is(true)); testAspectDef.triggered = false; testDependantAspectDef.triggered = false; binding.updateFromPmo(); assertThat(testAspectDef.triggered, is(true)); assertThat(testDependantAspectDef.triggered, is(true)); } |
### Question:
ModelObjects { public static boolean isAccessible(Object pmo, String modelObjectName) { return getModelObjectAccessMember(pmo, modelObjectName).isPresent(); } private ModelObjects(Class<?> pmoClass, String modelObjectName); static Supplier<Object> supplierFor(Object pmo, String modelObjectName); static boolean isAccessible(Object pmo, String modelObjectName); }### Answer:
@Test public void testHasModelObjectAnnotatedMethod() { assertThat(ModelObjects.isAccessible(new TestPmo(), ModelObject.DEFAULT_NAME), is(true)); assertThat(ModelObjects.isAccessible(new PmoWithNamedModelObject(), PmoWithNamedModelObject.MODEL_OBJECT), is(true)); assertThat(ModelObjects.isAccessible(new PmoWithNamedModelObject(), ModelObject.DEFAULT_NAME), is(true)); }
@Test public void testHasModelObjectAnnotatedMethod_noAnnotation() { assertThat(ModelObjects.isAccessible(new Object(), ModelObject.DEFAULT_NAME), is(false)); }
@Test public void testHasModelObjectAnnotatedMethod_noMatchingAnnotation() { assertThat(ModelObjects.isAccessible(new PmoWithNamedModelObject(), "someOtherName"), is(false)); assertThat(ModelObjects.isAccessible(new Object(), "FooBar"), is(false)); } |
### Question:
BoundPropertyAnnotationReader { public static boolean isBoundPropertyPresent(AnnotatedElement annotatedElement) { return BOUND_PROPERTY_ANNOTATION.isPresentOnAnyAnnotationOn(annotatedElement); } private BoundPropertyAnnotationReader(); static boolean isBoundPropertyPresent(AnnotatedElement annotatedElement); static BoundProperty getBoundProperty(AnnotatedElement annotatedElement); static Optional<BoundProperty> findBoundProperty(AnnotatedElement annotatedElement); static BoundProperty getBoundProperty(A annotation,
AnnotatedElement annotatedElement); }### Answer:
@Test public void testIsBoundPropertyPresent() throws Exception { assertThat(BoundPropertyAnnotationReader.isBoundPropertyPresent(BoundPropertyAnnotationReaderTest.class), is(false)); assertThat(BoundPropertyAnnotationReader.isBoundPropertyPresent(BoundPropertyAnnotationReaderTest.class .getMethod("testIsBoundPropertyPresent")), is(false)); assertThat(BoundPropertyAnnotationReader.isBoundPropertyPresent(BoundPropertyAnnotationReaderTest.class .getField("foo")), is(false)); assertThat(BoundPropertyAnnotationReader.isBoundPropertyPresent(TestBind.class), is(false)); assertThat(BoundPropertyAnnotationReader.isBoundPropertyPresent(ClassWithBoundPropertyAnnotations.class), is(false)); assertThat(BoundPropertyAnnotationReader.isBoundPropertyPresent(ClassWithBoundPropertyAnnotations.class .getMethod("getComponent")), is(true)); assertThat(BoundPropertyAnnotationReader.isBoundPropertyPresent(ClassWithBoundPropertyAnnotations.class .getField("component")), is(true)); assertThat(BoundPropertyAnnotationReader.isBoundPropertyPresent(ClassWithBoundPropertyAnnotations.class .getField("componentWithDefectBoundPropertyCreator")), is(true)); assertThat(BoundPropertyAnnotationReader.isBoundPropertyPresent(ClassWithBoundPropertyAnnotations.class .getField("componentWithUninstatiableBoundPropertyCreator")), is(true)); }
@Test public void testIsBoundPropertyPresent_multipleBoundPropertyCreators() throws Exception { assertTrue(BoundPropertyAnnotationReader.isBoundPropertyPresent(ClassWithBoundPropertyAnnotations.class .getField("componentWithMultipleBoundProperties"))); } |
### Question:
UIElementAnnotationReader { @Deprecated public static boolean hasModelObjectAnnotation(Object pmo, String modelObjectName) { try { return ModelObjects.isAccessible(pmo, modelObjectName); } catch (org.linkki.core.binding.descriptor.modelobject.ModelObjects.ModelObjectAnnotationException e) { throw new ModelObjectAnnotationException(e.getMessage()); } } UIElementAnnotationReader(Class<?> annotatedClass); PropertyElementDescriptors findDescriptors(String propertyName); Stream<PropertyElementDescriptors> getUiElements(); @Deprecated static Supplier<?> getModelObjectSupplier(Object pmo, String modelObjectName); @Deprecated static boolean hasModelObjectAnnotation(Object pmo, String modelObjectName); }### Answer:
@SuppressWarnings("deprecation") @Test public void testHasModelObjectAnnotatedMethod() { assertThat(UIElementAnnotationReader.hasModelObjectAnnotation(new TestPmo(), ModelObject.DEFAULT_NAME), is(true)); assertThat(UIElementAnnotationReader.hasModelObjectAnnotation(new PmoWithNamedModelObject(), PmoWithNamedModelObject.MODEL_OBJECT), is(true)); assertThat(UIElementAnnotationReader.hasModelObjectAnnotation(new PmoWithNamedModelObject(), ModelObject.DEFAULT_NAME), is(true)); }
@SuppressWarnings("deprecation") @Test public void testHasModelObjectAnnotatedMethod_noAnnotation() { assertThat(UIElementAnnotationReader.hasModelObjectAnnotation(new Object(), ModelObject.DEFAULT_NAME), is(false)); }
@SuppressWarnings("deprecation") @Test public void testHasModelObjectAnnotatedMethod_noMatchingAnnotation() { assertThat(UIElementAnnotationReader.hasModelObjectAnnotation(new PmoWithNamedModelObject(), "someOtherName"), is(false)); assertThat(UIElementAnnotationReader.hasModelObjectAnnotation(new Object(), "FooBar"), is(false)); } |
### Question:
Sequence implements Iterable<T> { public static <T> Sequence<T> empty() { return new Sequence<>(); } private Sequence(); private Sequence(Collection<T> collection); @SuppressWarnings("unchecked") static Sequence<T> of(Collection<? extends T> elements); @SafeVarargs static Sequence<T> of(T... elements); static Sequence<T> empty(); @CheckReturnValue Sequence<T> with(Collection<T> elements); Sequence<T> withNewElementsFrom(Collection<T> elements); @CheckReturnValue final Sequence<T> with(Sequence<T> sequence); @CheckReturnValue @SafeVarargs final Sequence<T> with(T... newElements); @SafeVarargs @CheckReturnValue final Sequence<T> withIf(boolean condition, Supplier<T>... suppliers); @CheckReturnValue final Sequence<T> withIf(boolean condition, Supplier<T> supplier); List<T> list(); @Override Iterator<T> iterator(); Stream<T> stream(); @Override String toString(); static Collector<T, ?, Sequence<T>> collect(); }### Answer:
@Test public void testEmpty() { Sequence<Object> sequence = Sequence.empty(); assertThat(sequence.list(), is(Collections.emptyList())); } |
### Question:
UIElementAnnotationReader { public Stream<PropertyElementDescriptors> getUiElements() { validateNoDuplicatePosition(); return descriptorsByProperty.values().stream() .filter(PropertyElementDescriptors::isNotEmpty) .sorted(Comparator.comparing(PropertyElementDescriptors::getPosition)); } UIElementAnnotationReader(Class<?> annotatedClass); PropertyElementDescriptors findDescriptors(String propertyName); Stream<PropertyElementDescriptors> getUiElements(); @Deprecated static Supplier<?> getModelObjectSupplier(Object pmo, String modelObjectName); @Deprecated static boolean hasModelObjectAnnotation(Object pmo, String modelObjectName); }### Answer:
@Test public void testGetUiElements_DynamicFields() { UIElementAnnotationReader uiElementAnnotationReader = new UIElementAnnotationReader(DynamicFieldPmo.class); List<PropertyElementDescriptors> uiElements = uiElementAnnotationReader.getUiElements() .collect(Collectors.toList()); assertThat(uiElements.size(), is(1)); PropertyElementDescriptors elementDescriptors = uiElements.get(0); ElementDescriptor fooDescriptor = elementDescriptors .getDescriptor(new DynamicFieldPmo(Type.FOO)); assertThat(fooDescriptor, is(notNullValue())); assertThat(fooDescriptor.getBoundProperty().getModelAttribute(), is("foo")); ElementDescriptor barDescriptor = elementDescriptors .getDescriptor(new DynamicFieldPmo(Type.BAR)); assertThat(barDescriptor, is(notNullValue())); assertThat(barDescriptor.getBoundProperty().getModelAttribute(), is("bar")); } |
### Question:
PropertyElementDescriptors { public int getPosition() { return position; } PropertyElementDescriptors(String pmoPropertyName); int getPosition(); String getPmoPropertyName(); ElementDescriptor getDescriptor(Object pmo); void addAspect(List<LinkkiAspectDefinition> aspectDefs); boolean isNotEmpty(); List<LinkkiAspectDefinition> getAllAspects(); }### Answer:
@Test public void testGetPosition_WithoutDescriptor() { PropertyElementDescriptors descriptors = new PropertyElementDescriptors(TestPmo.SINGLE_PMO_PROPERTY); assertThat(descriptors.getPosition(), is(0)); } |
### Question:
PropertyElementDescriptors { public String getPmoPropertyName() { return pmoPropertyName; } PropertyElementDescriptors(String pmoPropertyName); int getPosition(); String getPmoPropertyName(); ElementDescriptor getDescriptor(Object pmo); void addAspect(List<LinkkiAspectDefinition> aspectDefs); boolean isNotEmpty(); List<LinkkiAspectDefinition> getAllAspects(); }### Answer:
@Test public void testGetPmoPropertyName() { PropertyElementDescriptors descriptors = new PropertyElementDescriptors(TestPmo.SINGLE_PMO_PROPERTY); assertThat(descriptors.getPmoPropertyName(), is(TestPmo.SINGLE_PMO_PROPERTY)); } |
### Question:
Sequence implements Iterable<T> { @Override public String toString() { return list.toString(); } private Sequence(); private Sequence(Collection<T> collection); @SuppressWarnings("unchecked") static Sequence<T> of(Collection<? extends T> elements); @SafeVarargs static Sequence<T> of(T... elements); static Sequence<T> empty(); @CheckReturnValue Sequence<T> with(Collection<T> elements); Sequence<T> withNewElementsFrom(Collection<T> elements); @CheckReturnValue final Sequence<T> with(Sequence<T> sequence); @CheckReturnValue @SafeVarargs final Sequence<T> with(T... newElements); @SafeVarargs @CheckReturnValue final Sequence<T> withIf(boolean condition, Supplier<T>... suppliers); @CheckReturnValue final Sequence<T> withIf(boolean condition, Supplier<T> supplier); List<T> list(); @Override Iterator<T> iterator(); Stream<T> stream(); @Override String toString(); static Collector<T, ?, Sequence<T>> collect(); }### Answer:
@Test public void testToString() { Sequence<Integer> sequence = Sequence.of(1, 2, 3); assertThat(sequence.toString(), is("[1, 2, 3]")); } |
### Question:
PropertyElementDescriptors { public ElementDescriptor getDescriptor(Object pmo) { ElementDescriptor descriptor = findDescriptor(pmo); descriptor.addAspectDefinitions(additionalAspects); return descriptor; } PropertyElementDescriptors(String pmoPropertyName); int getPosition(); String getPmoPropertyName(); ElementDescriptor getDescriptor(Object pmo); void addAspect(List<LinkkiAspectDefinition> aspectDefs); boolean isNotEmpty(); List<LinkkiAspectDefinition> getAllAspects(); }### Answer:
@Test public void testGetDescriptor_WithoutDescriptor_NoComponentTypeMethod() { PropertyElementDescriptors descriptors = new PropertyElementDescriptors(TestPmo.SINGLE_PMO_PROPERTY); Assertions.assertThrows(IllegalStateException.class, () -> { descriptors.getDescriptor(new TestPmo()); }); }
@Test public void testGetDescriptor_WithoutDescriptor_WithComponentTypeMethod() { PropertyElementDescriptors descriptors = new PropertyElementDescriptors(TestPmo.DUAL_PMO_PROPERTY); Assertions.assertThrows(IllegalStateException.class, () -> { descriptors.getDescriptor(new TestPmo()); }); } |
### Question:
PropertyElementDescriptors { public void addAspect(List<LinkkiAspectDefinition> aspectDefs) { additionalAspects.addAll(aspectDefs); } PropertyElementDescriptors(String pmoPropertyName); int getPosition(); String getPmoPropertyName(); ElementDescriptor getDescriptor(Object pmo); void addAspect(List<LinkkiAspectDefinition> aspectDefs); boolean isNotEmpty(); List<LinkkiAspectDefinition> getAllAspects(); }### Answer:
@Test public void testAddAspect() { PropertyElementDescriptors descriptors = new PropertyElementDescriptors(TestPmo.SINGLE_PMO_PROPERTY); assertThat(descriptors.getAllAspects(), is(empty())); EnabledAspectDefinition enabledAspectDefinition = new EnabledAspectDefinition(EnabledType.ENABLED); descriptors.addAspect(Arrays.<LinkkiAspectDefinition> asList(enabledAspectDefinition)); assertThat(descriptors.getAllAspects(), contains(enabledAspectDefinition)); } |
### Question:
PropertyElementDescriptors { public boolean isNotEmpty() { return !descriptors.isEmpty(); } PropertyElementDescriptors(String pmoPropertyName); int getPosition(); String getPmoPropertyName(); ElementDescriptor getDescriptor(Object pmo); void addAspect(List<LinkkiAspectDefinition> aspectDefs); boolean isNotEmpty(); List<LinkkiAspectDefinition> getAllAspects(); }### Answer:
@Test public void testIsNotEmpty() { PropertyElementDescriptors descriptors = new PropertyElementDescriptors(TestPmo.SINGLE_PMO_PROPERTY); assertThat(descriptors.isNotEmpty(), is(false)); descriptors.addAspect(Arrays.<LinkkiAspectDefinition> asList(new EnabledAspectDefinition(EnabledType.ENABLED))); assertThat(descriptors.isNotEmpty(), is(false)); descriptors.addDescriptor(TestUIAnnotation.class, new ElementDescriptor(0, TestLinkkiComponentDefinition.create(), BoundProperty.of(TestPmo.SINGLE_PMO_PROPERTY), Collections.emptyList()), TestPmo.class); assertThat(descriptors.isNotEmpty()); } |
### Question:
PropertyElementDescriptors { public List<LinkkiAspectDefinition> getAllAspects() { return Stream.concat( descriptors.values().stream() .map(d -> d.getAspectDefinitions()) .flatMap(Collection::stream), additionalAspects.stream()) .collect(toList()); } PropertyElementDescriptors(String pmoPropertyName); int getPosition(); String getPmoPropertyName(); ElementDescriptor getDescriptor(Object pmo); void addAspect(List<LinkkiAspectDefinition> aspectDefs); boolean isNotEmpty(); List<LinkkiAspectDefinition> getAllAspects(); }### Answer:
@Test public void testGetAllAspects() { PropertyElementDescriptors descriptors = new PropertyElementDescriptors(TestPmo.DUAL_PMO_PROPERTY); EnabledAspectDefinition enabledAspectDefinition = new EnabledAspectDefinition(EnabledType.ENABLED); descriptors.addDescriptor(TestUIAnnotation.class, new ElementDescriptor(0, TestLinkkiComponentDefinition.create(), BoundProperty.of(TestPmo.DUAL_PMO_PROPERTY), Collections.singletonList(enabledAspectDefinition)), TestPmo.class); VisibleAspectDefinition visibleAspectDefinition = new VisibleAspectDefinition(VisibleType.VISIBLE); descriptors.addDescriptor(AnotherTestUIAnnotation.class, new ElementDescriptor(0, TestLinkkiComponentDefinition.create(), BoundProperty.of(TestPmo.DUAL_PMO_PROPERTY), Collections.singletonList(visibleAspectDefinition)), TestPmo.class); TestComponentClickAspectDefinition clickAspectDefinition = new TestComponentClickAspectDefinition(); descriptors.addAspect(Arrays.<LinkkiAspectDefinition> asList(clickAspectDefinition)); assertThat(descriptors.getAllAspects(), containsInAnyOrder(enabledAspectDefinition, visibleAspectDefinition, clickAspectDefinition)); } |
### Question:
AspectAnnotationReader { public static <UI_ANNOTATION extends Annotation> List<LinkkiAspectDefinition> createAspectDefinitionsFrom( UI_ANNOTATION uiAnnotation) { return createAspectDefinitionsStreamFrom(uiAnnotation) .collect(Collectors.toList()); } private AspectAnnotationReader(); static List<LinkkiAspectDefinition> createAspectDefinitionsFrom(
UI_ANNOTATION uiAnnotation); static List<LinkkiAspectDefinition> createAspectDefinitionsFor(AnnotatedElement annotatedElement); static List<LinkkiAspectDefinition> createAspectDefinitionsFor(Annotation componentDefAnnotation,
AnnotatedElement annotatedElement); }### Answer:
@Test public void testCreateAspectDefinitionsFrom() throws NoSuchMethodException, SecurityException { TestAnnotation annotationToTest = TestClass.class.getMethod("something").getAnnotation(TestAnnotation.class); List<LinkkiAspectDefinition> definitions = AspectAnnotationReader .createAspectDefinitionsFrom(annotationToTest); assertThat(definitions.size(), is(2)); LinkkiAspectDefinition definition = definitions.get(0); assertThat(definition, is(instanceOf(TestAspectDefinition.class))); assertThat(definition, isInitializedWith(TestAnnotation.class)); LinkkiAspectDefinition anotherDefinition = definitions.get(1); assertThat(anotherDefinition, is(instanceOf(AnotherTestAspectDefinition.class))); assertThat(anotherDefinition, isInitializedWith(TestAnnotation.class)); } |
### Question:
Services { public static <S> S get(Class<S> serviceClass) { @SuppressWarnings("unchecked") S service = (S)INSTANCES.computeIfAbsent(serviceClass, sc -> { ServiceLoader<?> serviceLoader = ServiceLoader.load(sc); return StreamSupport.stream(serviceLoader.spliterator(), false).reduce((f1, f2) -> { throw new IllegalStateException( "Multiple implementations of " + sc.getName() + " found on the classpath: " + f1.getClass() + " and " + f2.getClass()); }).orElseThrow(() -> new IllegalStateException( "No implementation of " + sc.getName() + " found on the classpath.")); }); return service; } private Services(); static S get(Class<S> serviceClass); }### Answer:
@Test public void testGetSingleImplementation() { assertThat(Services.get(InterfaceWithSingleImplementation.class), is(instanceOf(SingleImplementation.class))); }
@Test public void testGetNoImplementation() { Assertions.assertThrows(IllegalStateException.class, () -> { Services.get(InterfaceWithoutImplementation.class); }); }
@Test public void testGetMultipleImplementations() { Assertions.assertThrows(IllegalStateException.class, () -> { Services.get(InterfaceWithMultipleImplementations.class); }); } |
### Question:
StaticModelToUiAspectDefinition extends ModelToUiAspectDefinition<VALUE_TYPE> { @Override public Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper) { super.createUiUpdater(propertyDispatcher, componentWrapper).apply(); return Handler.NOP_HANDLER; } @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); }### Answer:
@SuppressWarnings("unchecked") @Test public void testCreateUiUpdater() { when(propertyDispatcher.pull(any(Aspect.class))).thenReturn(true); assertThat(componentWrapper.getComponent().isEnabled(), is(false)); Handler handler = aspectDefinition.createUiUpdater(propertyDispatcher, componentWrapper); verify(propertyDispatcher, times(1)).pull(any(Aspect.class)); assertThat(componentWrapper.getComponent().isEnabled(), is(true)); handler.apply(); verify(propertyDispatcher, times(1)).pull(any(Aspect.class)); }
@Test public void testCreateUiUpdater_WrapsExceptionInPull() { when(propertyDispatcher.pull(Mockito.any())).thenThrow(RuntimeException.class); Assertions.assertThrows(LinkkiBindingException.class, () -> { aspectDefinition.createUiUpdater(propertyDispatcher, componentWrapper); }); } |
### Question:
ModelToUiAspectDefinition implements LinkkiAspectDefinition { @Override public Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper) { Consumer<V> setter = createComponentValueSetter(componentWrapper); Aspect<V> aspect = createAspect(); return () -> { try { setter.accept(propertyDispatcher.pull(aspect)); } catch (RuntimeException e) { handleUiUpdateException(e, propertyDispatcher, aspect); } }; } @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); abstract Aspect<V> createAspect(); abstract Consumer<V> createComponentValueSetter(ComponentWrapper componentWrapper); }### Answer:
@SuppressWarnings("unchecked") @Test public void testCreateUiUpdater() { when(propertyDispatcher.pull(any(Aspect.class))).thenReturn(true); Handler handler = aspectDefinition.createUiUpdater(propertyDispatcher, componentWrapper); assertThat(componentWrapper.getComponent().isEnabled(), is(false)); handler.apply(); verify(propertyDispatcher, times(1)).pull(any(Aspect.class)); assertThat(componentWrapper.getComponent().isEnabled(), is(true)); handler.apply(); verify(propertyDispatcher, times(2)).pull(any(Aspect.class)); }
@Test public void testCreateUiUpdater_WrapsExceptionInPull() { when(propertyDispatcher.pull(any())).thenThrow(RuntimeException.class); Handler handler = aspectDefinition.createUiUpdater(propertyDispatcher, componentWrapper); Assertions.assertThrows(LinkkiBindingException.class, () -> { handler.apply(); }); } |
### Question:
ModelToUiAspectDefinition implements LinkkiAspectDefinition { public abstract Aspect<V> createAspect(); @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); abstract Aspect<V> createAspect(); abstract Consumer<V> createComponentValueSetter(ComponentWrapper componentWrapper); }### Answer:
@Test public void testCreateAspect() { Aspect<Boolean> createdAspect = aspectDefinition.createAspect(); assertThat(createdAspect.getName(), is(TestModelToUiAspectDefinition.NAME)); assertThat(createdAspect.getValue(), is(true)); } |
### Question:
ModelToUiAspectDefinition implements LinkkiAspectDefinition { public abstract Consumer<V> createComponentValueSetter(ComponentWrapper componentWrapper); @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); abstract Aspect<V> createAspect(); abstract Consumer<V> createComponentValueSetter(ComponentWrapper componentWrapper); }### Answer:
@Test public void testCreateComponentValueSetter() { Consumer<Boolean> setter = aspectDefinition.createComponentValueSetter(componentWrapper); assertThat(componentWrapper.getComponent().isEnabled(), is(false)); setter.accept(true); assertThat(componentWrapper.getComponent().isEnabled(), is(true)); } |
### Question:
CompositeAspectDefinition implements LinkkiAspectDefinition { @Override public Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper) { return aspectDefinitions.stream() .filter(d -> d.supports(componentWrapper.getType())) .map(lad -> lad.createUiUpdater(propertyDispatcher, componentWrapper)) .reduce(Handler.NOP_HANDLER, Handler::andThen); } CompositeAspectDefinition(@NonNull LinkkiAspectDefinition... aspectDefinitions); CompositeAspectDefinition(List<LinkkiAspectDefinition> aspectDefinitions); @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); @Override void initModelUpdate(PropertyDispatcher propertyDispatcher,
ComponentWrapper componentWrapper,
Handler modelUpdated); @Override boolean supports(WrapperType type); }### Answer:
@Test public void testCreateUiUpdater() { CompositeAspectDefinition composite = new CompositeAspectDefinition(aspect1, aspect2NotSupported, aspect3); composite.createUiUpdater(propertyDispatcher, componentWrapper); verify(aspect1).supports(WrapperType.FIELD); verify(aspect2NotSupported).supports(WrapperType.FIELD); verify(aspect3).supports(WrapperType.FIELD); verify(aspect1).createUiUpdater(propertyDispatcher, componentWrapper); verify(aspect2NotSupported, never()).createUiUpdater(propertyDispatcher, componentWrapper); verify(aspect3).createUiUpdater(propertyDispatcher, componentWrapper); } |
### Question:
CompositeAspectDefinition implements LinkkiAspectDefinition { @Override public void initModelUpdate(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper, Handler modelUpdated) { aspectDefinitions .stream() .filter(d -> d.supports(componentWrapper.getType())) .forEach(lad -> { try { lad.initModelUpdate(propertyDispatcher, componentWrapper, modelUpdated); } catch (RuntimeException e) { throw new LinkkiBindingException( e.getMessage() + " while init model update of " + lad.getClass().getSimpleName() + " for " + componentWrapper + " <=> " + propertyDispatcher, e); } }); } CompositeAspectDefinition(@NonNull LinkkiAspectDefinition... aspectDefinitions); CompositeAspectDefinition(List<LinkkiAspectDefinition> aspectDefinitions); @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); @Override void initModelUpdate(PropertyDispatcher propertyDispatcher,
ComponentWrapper componentWrapper,
Handler modelUpdated); @Override boolean supports(WrapperType type); }### Answer:
@Test public void testInitModelUpdate() { CompositeAspectDefinition composite = new CompositeAspectDefinition(aspect1, aspect2NotSupported, aspect3); composite.initModelUpdate(propertyDispatcher, componentWrapper, modelUpdated); verify(aspect1).supports(WrapperType.FIELD); verify(aspect2NotSupported).supports(WrapperType.FIELD); verify(aspect3).supports(WrapperType.FIELD); verify(aspect1).initModelUpdate(propertyDispatcher, componentWrapper, modelUpdated); verify(aspect2NotSupported, never()).initModelUpdate(propertyDispatcher, componentWrapper, modelUpdated); verify(aspect3).initModelUpdate(propertyDispatcher, componentWrapper, modelUpdated); } |
### Question:
CompositeAspectDefinition implements LinkkiAspectDefinition { @Override public boolean supports(WrapperType type) { return aspectDefinitions.stream() .anyMatch(d -> d.supports(type)); } CompositeAspectDefinition(@NonNull LinkkiAspectDefinition... aspectDefinitions); CompositeAspectDefinition(List<LinkkiAspectDefinition> aspectDefinitions); @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); @Override void initModelUpdate(PropertyDispatcher propertyDispatcher,
ComponentWrapper componentWrapper,
Handler modelUpdated); @Override boolean supports(WrapperType type); }### Answer:
@Test public void testSupports() { assertTrue(new CompositeAspectDefinition(aspect1, aspect2NotSupported, aspect3).supports(WrapperType.FIELD)); assertFalse(new CompositeAspectDefinition(aspect1, aspect2NotSupported, aspect3).supports(WrapperType.LAYOUT)); assertFalse(new CompositeAspectDefinition(aspect2NotSupported).supports(WrapperType.FIELD)); } |
### Question:
Classes { public static <T> T instantiate(Class<T> clazz) { try { return clazz .getConstructor() .newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalArgumentException( String.format("Cannot instantiate %s", clazz.getName()), e); } } private Classes(); static T instantiate(Class<T> clazz); }### Answer:
@Test public void testInstantiate() { assertThat(Classes.instantiate(NoArg.class), is(instanceOf(NoArg.class))); }
@Test public void testInstantiate_NoNoArgs() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Classes.instantiate(WithArg.class); }); }
@Test public void testInstantiate_PrivateConstructor() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Classes.instantiate(PrivateConstructor.class); }); } |
### Question:
BehaviorDependentDispatcher extends AbstractPropertyDispatcherDecorator { @SuppressWarnings("unchecked") @Override public <T> T pull(Aspect<T> aspect) { if (aspect.getName().equals(VisibleAspectDefinition.NAME) && !isConsensus(forBoundObjectAndProperty(PropertyBehavior::isVisible))) { return (T)Boolean.FALSE; } else { return super.pull(aspect); } } BehaviorDependentDispatcher(PropertyDispatcher wrappedDispatcher,
PropertyBehaviorProvider provider); @Override MessageList getMessages(MessageList messageList); @SuppressWarnings("unchecked") @Override T pull(Aspect<T> aspect); @Override boolean isPushable(Aspect<T> aspect); }### Answer:
@Test public void testReturnTrueWithNoBehaviors() { assertThat(behaviorDispatcher.pull(Aspect.of(VisibleAspectDefinition.NAME)), is(true)); }
@Test public void testNullBoundObject_visible() { wrappedDispatcher.setBoundObject(null); behaviorDispatcher = new BehaviorDependentDispatcher(wrappedDispatcher, PropertyBehaviorProvider.with(PropertyBehavior.visible(() -> false))); Assertions.assertThrows(NullPointerException.class, () -> { behaviorDispatcher.pull(Aspect.of(VisibleAspectDefinition.NAME)); }); }
@Test public void testNullBoundObject_writable() { wrappedDispatcher.setBoundObject(null); behaviorDispatcher = new BehaviorDependentDispatcher(wrappedDispatcher, PropertyBehaviorProvider.with(PropertyBehavior.writable(() -> false))); Assertions.assertThrows(NullPointerException.class, () -> { behaviorDispatcher.pull(Aspect.of(VisibleAspectDefinition.NAME)); }); }
@Test public void testNonConsensus_visible() { behaviorDispatcher = new BehaviorDependentDispatcher(wrappedDispatcher, PropertyBehaviorProvider.with(PropertyBehavior.visible(() -> false))); assertThat(behaviorDispatcher.pull(Aspect.of(VisibleAspectDefinition.NAME)), is(false)); } |
### Question:
BehaviorDependentDispatcher extends AbstractPropertyDispatcherDecorator { @Override public MessageList getMessages(MessageList messageList) { if (isConsensus(forBoundObjectAndProperty(PropertyBehavior::isShowValidationMessages))) { return super.getMessages(messageList); } else { return new MessageList(); } } BehaviorDependentDispatcher(PropertyDispatcher wrappedDispatcher,
PropertyBehaviorProvider provider); @Override MessageList getMessages(MessageList messageList); @SuppressWarnings("unchecked") @Override T pull(Aspect<T> aspect); @Override boolean isPushable(Aspect<T> aspect); }### Answer:
@Test public void testNullBoundObject_messages() { wrappedDispatcher.setBoundObject(null); behaviorDispatcher = new BehaviorDependentDispatcher(wrappedDispatcher, PropertyBehaviorProvider.with(PropertyBehavior.showValidationMessages(() -> false))); Assertions.assertThrows(NullPointerException.class, () -> { behaviorDispatcher.getMessages(new MessageList()); }); }
@Test public void testNonConsensus_messages() { behaviorDispatcher = new BehaviorDependentDispatcher(wrappedDispatcher, PropertyBehaviorProvider.with(PropertyBehavior.showValidationMessages(() -> false))); MessageList messageList = new MessageList(Message.builder("Foo", Severity.ERROR) .invalidObject(new ObjectProperty(wrappedDispatcher.getBoundObject(), "prop")).code("4711").create()); assertThat(behaviorDispatcher.getMessages(messageList), is(emptyMessageList())); } |
### Question:
BehaviorDependentDispatcher extends AbstractPropertyDispatcherDecorator { @Override public <T> boolean isPushable(Aspect<T> aspect) { if (aspect.getName().equals(LinkkiAspectDefinition.VALUE_ASPECT_NAME) && !isConsensus(forBoundObjectAndProperty(PropertyBehavior::isWritable))) { return false; } else { return super.isPushable(aspect); } } BehaviorDependentDispatcher(PropertyDispatcher wrappedDispatcher,
PropertyBehaviorProvider provider); @Override MessageList getMessages(MessageList messageList); @SuppressWarnings("unchecked") @Override T pull(Aspect<T> aspect); @Override boolean isPushable(Aspect<T> aspect); }### Answer:
@Test public void testNonConsensus_writable() { behaviorDispatcher = new BehaviorDependentDispatcher(wrappedDispatcher, PropertyBehaviorProvider.with(PropertyBehavior.writable(() -> false))); assertThat(behaviorDispatcher.isPushable(Aspect.of(StringUtils.EMPTY)), is(false)); }
@Test public void testIsPushable_IgnoreOtherAspect() { behaviorDispatcher = new BehaviorDependentDispatcher(new TestPropertyDispatcher(), PropertyBehaviorProvider.with(PropertyBehavior.readOnly())); boolean pushable = behaviorDispatcher.isPushable(Aspect.of("any")); assertThat(pushable, is(true)); }
@Test public void testIsPushable_ReadOnly() { behaviorDispatcher = new BehaviorDependentDispatcher(new TestPropertyDispatcher(), PropertyBehaviorProvider.with(PropertyBehavior.readOnly())); boolean pushable = behaviorDispatcher.isPushable(Aspect.of("")); assertThat(pushable, is(false)); } |
### Question:
PropertyAccessorCache { @SuppressWarnings("unchecked") public static <T> PropertyAccessor<T, ?> get(Class<T> clazz, String property) { return (PropertyAccessor<T, ?>)ACCESSOR_CACHE.get(new CacheKey(clazz, property)); } private PropertyAccessorCache(); @SuppressWarnings("unchecked") static PropertyAccessor<T, ?> get(Class<T> clazz, String property); }### Answer:
@Test public void testGet_ReturnsSameAccessorOnSubsequentCalls() { PropertyAccessor<TestObject, ?> propertyAccessor = PropertyAccessorCache.get(TestObject.class, TestObject.STRING_PROPERTY); assertThat(propertyAccessor.getPropertyName(), is(TestObject.STRING_PROPERTY)); assertThat(PropertyAccessorCache.get(TestObject.class, TestObject.STRING_PROPERTY), is(sameInstance(propertyAccessor))); } |
### Question:
ReadMethod extends AbstractMethod<T> { public V readValue(T boundObject) { if (canRead()) { return readValueWithExceptionHandling(boundObject); } else { throw new IllegalStateException( "Cannot find getter method for " + boundObject.getClass().getName() + "#" + getPropertyName()); } } ReadMethod(PropertyAccessDescriptor<T, V> descriptor); boolean canRead(); V readValue(T boundObject); @SuppressWarnings("unchecked") Class<V> getReturnType(); }### Answer:
@Test public void testReadValue() { TestObject testObject = new TestObject(); PropertyAccessDescriptor<TestObject, Long> descriptor = new PropertyAccessDescriptor<>(TestObject.class, TestObject.READ_ONLY_LONG_PROPERTY); ReadMethod<TestObject, Long> readMethod = descriptor.createReadMethod(); assertEquals(42, readMethod.readValue(testObject).longValue()); } |
### Question:
ReadMethod extends AbstractMethod<T> { public boolean canRead() { return hasMethod(); } ReadMethod(PropertyAccessDescriptor<T, V> descriptor); boolean canRead(); V readValue(T boundObject); @SuppressWarnings("unchecked") Class<V> getReturnType(); }### Answer:
@Test public void testReadValue_NoGetterMethod() { PropertyAccessDescriptor<?, ?> descriptor = new PropertyAccessDescriptor<>(TestObject.class, TestObject.DO_SOMETHING_METHOD); ReadMethod<?, ?> readMethod = descriptor.createReadMethod(); assertFalse(readMethod.canRead()); }
@Test public void testReadValue_VoidGetterMethod() { PropertyAccessDescriptor<?, ?> descriptor = new PropertyAccessDescriptor<>(TestObject.class, "void"); ReadMethod<?, ?> readMethod = descriptor.createReadMethod(); assertFalse(readMethod.canRead()); } |
### Question:
WriteMethod extends AbstractMethod<T> { public void writeValue(T target, @CheckForNull V value) { try { setter().accept(target, value); } catch (IllegalArgumentException | IllegalStateException e) { throw new LinkkiBindingException( "Cannot write value: " + value + " in " + getBoundClass() + "#" + getPropertyName(), e); } } WriteMethod(PropertyAccessDescriptor<T, V> descriptor); boolean canWrite(); void writeValue(T target, @CheckForNull V value); }### Answer:
@Test public void testWriteValue() { TestObject testObject = new TestObject(); descriptor = new PropertyAccessDescriptor<>(TestObject.class, TestObject.BOOLEAN_PROPERTY); WriteMethod<TestObject, Boolean> writeMethod = descriptor.createWriteMethod(); writeMethod.writeValue(testObject, true); } |
### Question:
PropertyAccessor { public void setPropertyValue(T boundObject, @CheckForNull V value) { writeMethod.writeValue(boundObject, value); } PropertyAccessor(Class<? extends T> boundClass, String propertyName); String getPropertyName(); V getPropertyValue(T boundObject); void setPropertyValue(T boundObject, @CheckForNull V value); void invoke(T boundObject); boolean canWrite(); boolean canInvoke(); boolean canRead(); Class<?> getValueClass(); }### Answer:
@Test public void testWrite() { assertEquals(STRING_PROPERTY_INITIAL_VALUE, testObject.getStringProperty()); stringAccessor.setPropertyValue(testObject, "anotherValue"); assertEquals("anotherValue", testObject.getStringProperty()); }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testWriteWrongType() { Assertions.assertThrows(RuntimeException.class, () -> { ((PropertyAccessor)stringAccessor).setPropertyValue(testObject, 5); }); }
@Test public void testSetPropertyValue_readOnlyProperty() { TestObject testObject2 = new TestObject(); PropertyAccessor<TestObject, Long> accessor = new PropertyAccessor<>(TestObject.class, TestObject.READ_ONLY_LONG_PROPERTY); Assertions.assertThrows(LinkkiBindingException.class, () -> { accessor.setPropertyValue(testObject2, 5L); }); } |
### Question:
PropertyAccessor { public String getPropertyName() { return propertyName; } PropertyAccessor(Class<? extends T> boundClass, String propertyName); String getPropertyName(); V getPropertyValue(T boundObject); void setPropertyValue(T boundObject, @CheckForNull V value); void invoke(T boundObject); boolean canWrite(); boolean canInvoke(); boolean canRead(); Class<?> getValueClass(); }### Answer:
@Test public void testConstructor() { String boundProperty = stringAccessor.getPropertyName(); assertNotNull(boundProperty); } |
### Question:
PropertyAccessor { public boolean canRead() { return readMethod.canRead(); } PropertyAccessor(Class<? extends T> boundClass, String propertyName); String getPropertyName(); V getPropertyValue(T boundObject); void setPropertyValue(T boundObject, @CheckForNull V value); void invoke(T boundObject); boolean canWrite(); boolean canInvoke(); boolean canRead(); Class<?> getValueClass(); }### Answer:
@Test public void testCanRead() { TestObject testObject2 = new TestObject(); PropertyAccessor<TestObject, Long> propertyAccessor = new PropertyAccessor<>(TestObject.class, TestObject.READ_ONLY_LONG_PROPERTY); assertThat((propertyAccessor.canWrite()), is(false)); assertThat(propertyAccessor.canRead()); Long propertyValue = propertyAccessor.getPropertyValue(testObject2); assertEquals(42, propertyValue.longValue()); } |
### Question:
PropertyAccessor { public Class<?> getValueClass() { return readMethod.getReturnType(); } PropertyAccessor(Class<? extends T> boundClass, String propertyName); String getPropertyName(); V getPropertyValue(T boundObject); void setPropertyValue(T boundObject, @CheckForNull V value); void invoke(T boundObject); boolean canWrite(); boolean canInvoke(); boolean canRead(); Class<?> getValueClass(); }### Answer:
@Test public void testGetValueClass() { PropertyAccessor<TestObject, Long> accessor = new PropertyAccessor<>(TestObject.class, TestObject.READ_ONLY_LONG_PROPERTY); assertEquals(long.class, accessor.getValueClass()); }
@Test public void testGetValueClass2() { PropertyAccessor<TestObject, Boolean> accessor = new PropertyAccessor<>(TestObject.class, TestObject.BOOLEAN_PROPERTY); assertEquals(boolean.class, accessor.getValueClass()); }
@Test public void testGetValueClassIllegalProperty() { PropertyAccessor<TestObject, ?> accessor = new PropertyAccessor<>(TestObject.class, "illegalProperty"); Assertions.assertThrows(IllegalArgumentException.class, () -> { accessor.getValueClass(); }); } |
### Question:
AbstractMethod { protected boolean hasMethod() { return getReflectionMethod().isPresent(); } AbstractMethod(PropertyAccessDescriptor<T, ?> descriptor, Supplier<Optional<Method>> methodSupplier); }### Answer:
@Test public void testHasNoMethod() { when(descriptor.getReflectionWriteMethod()).thenReturn(lazyCaching(Optional::empty)); AbstractMethod<?> writeMethod = new WriteMethod<>(descriptor); assertFalse(writeMethod.hasMethod()); } |
### Question:
PropertyNamingConvention { public String getValueProperty(String property) { return requireNonNull(property, "property must not be null"); } String getValueProperty(String property); String getEnabledProperty(String property); String getVisibleProperty(String property); String getMessagesProperty(String property); String getAvailableValuesProperty(String property); String getRequiredProperty(String property); String getCaptionProperty(String property); @Deprecated String getToolTipProperty(String property); String getComponentTypeProperty(String property); String getCombinedPropertyName(String property, String suffix); static final String ENABLED_PROPERTY_SUFFIX; static final String VISIBLE_PROPERTY_SUFFIX; static final String REQUIRED_PROPERTY_SUFFIX; static final String MESSAGES_PROPERTY_SUFFIX; static final String AVAILABLE_VALUES_PROPERTY_SUFFIX; static final String CAPTION_PROPERTY_SUFFIX; @Deprecated
static final String TOOLTIP_PROPERTY_SUFFIX; static final String COMPONENT_PROPERTY_SUFFIX; }### Answer:
@Test public void testGetValueProperty() { assertEquals("test", namingConvention.getValueProperty("test")); }
@Test public void testGetValueProperty_null() { Assertions.assertThrows(NullPointerException.class, () -> { namingConvention.getValueProperty(null); }); } |
### Question:
PropertyNamingConvention { public String getEnabledProperty(String property) { return getCombinedPropertyName(property, ENABLED_PROPERTY_SUFFIX); } String getValueProperty(String property); String getEnabledProperty(String property); String getVisibleProperty(String property); String getMessagesProperty(String property); String getAvailableValuesProperty(String property); String getRequiredProperty(String property); String getCaptionProperty(String property); @Deprecated String getToolTipProperty(String property); String getComponentTypeProperty(String property); String getCombinedPropertyName(String property, String suffix); static final String ENABLED_PROPERTY_SUFFIX; static final String VISIBLE_PROPERTY_SUFFIX; static final String REQUIRED_PROPERTY_SUFFIX; static final String MESSAGES_PROPERTY_SUFFIX; static final String AVAILABLE_VALUES_PROPERTY_SUFFIX; static final String CAPTION_PROPERTY_SUFFIX; @Deprecated
static final String TOOLTIP_PROPERTY_SUFFIX; static final String COMPONENT_PROPERTY_SUFFIX; }### Answer:
@Test public void testGetEnabledProperty() { assertEquals("testEnabled", namingConvention.getEnabledProperty("test")); }
@Test public void testGetEnabledProperty_empty() { assertEquals("enabled", namingConvention.getEnabledProperty(StringUtils.EMPTY)); }
@Test public void testGetEnabledProperty_null() { Assertions.assertThrows(NullPointerException.class, () -> { namingConvention.getEnabledProperty(null); }); } |
### Question:
PropertyNamingConvention { public String getVisibleProperty(String property) { return getCombinedPropertyName(property, VISIBLE_PROPERTY_SUFFIX); } String getValueProperty(String property); String getEnabledProperty(String property); String getVisibleProperty(String property); String getMessagesProperty(String property); String getAvailableValuesProperty(String property); String getRequiredProperty(String property); String getCaptionProperty(String property); @Deprecated String getToolTipProperty(String property); String getComponentTypeProperty(String property); String getCombinedPropertyName(String property, String suffix); static final String ENABLED_PROPERTY_SUFFIX; static final String VISIBLE_PROPERTY_SUFFIX; static final String REQUIRED_PROPERTY_SUFFIX; static final String MESSAGES_PROPERTY_SUFFIX; static final String AVAILABLE_VALUES_PROPERTY_SUFFIX; static final String CAPTION_PROPERTY_SUFFIX; @Deprecated
static final String TOOLTIP_PROPERTY_SUFFIX; static final String COMPONENT_PROPERTY_SUFFIX; }### Answer:
@Test public void testGetVisibleProperty() { assertEquals("testVisible", namingConvention.getVisibleProperty("test")); }
@Test public void testGetVisibleProperty_empty() { assertEquals("visible", namingConvention.getVisibleProperty(StringUtils.EMPTY)); }
@Test public void testGetVisibleProperty_null() { Assertions.assertThrows(NullPointerException.class, () -> { namingConvention.getVisibleProperty(null); }); } |
### Question:
PropertyNamingConvention { public String getMessagesProperty(String property) { return getCombinedPropertyName(property, MESSAGES_PROPERTY_SUFFIX); } String getValueProperty(String property); String getEnabledProperty(String property); String getVisibleProperty(String property); String getMessagesProperty(String property); String getAvailableValuesProperty(String property); String getRequiredProperty(String property); String getCaptionProperty(String property); @Deprecated String getToolTipProperty(String property); String getComponentTypeProperty(String property); String getCombinedPropertyName(String property, String suffix); static final String ENABLED_PROPERTY_SUFFIX; static final String VISIBLE_PROPERTY_SUFFIX; static final String REQUIRED_PROPERTY_SUFFIX; static final String MESSAGES_PROPERTY_SUFFIX; static final String AVAILABLE_VALUES_PROPERTY_SUFFIX; static final String CAPTION_PROPERTY_SUFFIX; @Deprecated
static final String TOOLTIP_PROPERTY_SUFFIX; static final String COMPONENT_PROPERTY_SUFFIX; }### Answer:
@Test public void testGetMessagesProperty() { assertEquals("testMessages", namingConvention.getMessagesProperty("test")); }
@Test public void testGetMessagesProperty_null() { Assertions.assertThrows(NullPointerException.class, () -> { namingConvention.getMessagesProperty(null); }); } |
### Question:
PropertyNamingConvention { public String getRequiredProperty(String property) { return getCombinedPropertyName(property, REQUIRED_PROPERTY_SUFFIX); } String getValueProperty(String property); String getEnabledProperty(String property); String getVisibleProperty(String property); String getMessagesProperty(String property); String getAvailableValuesProperty(String property); String getRequiredProperty(String property); String getCaptionProperty(String property); @Deprecated String getToolTipProperty(String property); String getComponentTypeProperty(String property); String getCombinedPropertyName(String property, String suffix); static final String ENABLED_PROPERTY_SUFFIX; static final String VISIBLE_PROPERTY_SUFFIX; static final String REQUIRED_PROPERTY_SUFFIX; static final String MESSAGES_PROPERTY_SUFFIX; static final String AVAILABLE_VALUES_PROPERTY_SUFFIX; static final String CAPTION_PROPERTY_SUFFIX; @Deprecated
static final String TOOLTIP_PROPERTY_SUFFIX; static final String COMPONENT_PROPERTY_SUFFIX; }### Answer:
@Test public void testGetRequiredProperty() { assertEquals("testRequired", namingConvention.getRequiredProperty("test")); }
@Test public void testGetRequiredProperty_null() { Assertions.assertThrows(NullPointerException.class, () -> { namingConvention.getRequiredProperty(null); }); } |
### Question:
PropertyNamingConvention { public String getAvailableValuesProperty(String property) { return getCombinedPropertyName(property, AVAILABLE_VALUES_PROPERTY_SUFFIX); } String getValueProperty(String property); String getEnabledProperty(String property); String getVisibleProperty(String property); String getMessagesProperty(String property); String getAvailableValuesProperty(String property); String getRequiredProperty(String property); String getCaptionProperty(String property); @Deprecated String getToolTipProperty(String property); String getComponentTypeProperty(String property); String getCombinedPropertyName(String property, String suffix); static final String ENABLED_PROPERTY_SUFFIX; static final String VISIBLE_PROPERTY_SUFFIX; static final String REQUIRED_PROPERTY_SUFFIX; static final String MESSAGES_PROPERTY_SUFFIX; static final String AVAILABLE_VALUES_PROPERTY_SUFFIX; static final String CAPTION_PROPERTY_SUFFIX; @Deprecated
static final String TOOLTIP_PROPERTY_SUFFIX; static final String COMPONENT_PROPERTY_SUFFIX; }### Answer:
@Test public void testGetAvailableValuesProperty() { assertEquals("testAvailableValues", namingConvention.getAvailableValuesProperty("test")); }
@Test public void testGetAvailableValuesProperty_null() { Assertions.assertThrows(NullPointerException.class, () -> { namingConvention.getAvailableValuesProperty(null); }); } |
### Question:
ReflectionPropertyDispatcher implements PropertyDispatcher { @Override public Class<?> getValueClass() { Object boundObject = getBoundObject(); if (boundObject != null && hasReadMethod(getProperty())) { Class<?> valueClass = getAccessor(getProperty()).getValueClass(); return valueClass; } else { return fallbackDispatcher.getValueClass(); } } ReflectionPropertyDispatcher(Supplier<?> boundObjectSupplier, String property,
PropertyDispatcher fallbackDispatcher); @Override String getProperty(); @CheckForNull @Override Object getBoundObject(); @Override Class<?> getValueClass(); @Override @SuppressWarnings("unchecked") V pull(Aspect<V> aspect); @Override void push(Aspect<V> aspect); @Override boolean isPushable(Aspect<V> aspect); @Override MessageList getMessages(MessageList messageList); @Override String toString(); }### Answer:
@Test public void testGetValueClass() { assertEquals(String.class, setupPmoDispatcher(ABC).getValueClass()); assertEquals(String.class, setupPmoDispatcher(XYZ).getValueClass()); assertEquals(Boolean.class, setupPmoDispatcher(OBJECT_BOOLEAN).getValueClass()); assertEquals(Boolean.TYPE, setupPmoDispatcher(PRIMITIVE_BOOLEAN).getValueClass()); } |
### Question:
BeanUtils { public static Stream<Method> getMethods(Class<?> clazz, Predicate<Method> predicate) { return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isSynthetic()) .filter(predicate); } private BeanUtils(); static BeanInfo getBeanInfo(Class<?> clazz); static Method getMethod(Class<?> clazz, String name, Class<?>... parameterTypes); static Optional<Method> getMethod(Class<?> clazz, Predicate<Method> predicate); static Stream<Method> getMethods(Class<?> clazz, Predicate<Method> predicate); static Field getDeclaredField(Class<?> clazz, String name); static Field getField(Class<?> clazz, String name); @CheckForNull static Object getValueFromField(Object object, String name); @CheckForNull static Object getValueFromField(Object object, Field field); static String getPropertyName(Method method); static String getPropertyName(Type returnType, String methodName); static final String GET_PREFIX; static final String SET_PREFIX; static final String IS_PREFIX; }### Answer:
@Test public void testGetMethods_AllMatchingMethodsAreFound() { Stream<Method> declaredMethods = BeanUtils.getMethods(Foo.class, (m) -> m.getName().equals("baz")); assertThat(declaredMethods.count(), is(2L)); } |
### Question:
BeanUtils { public static String getPropertyName(Method method) { return getPropertyName(method.getReturnType(), method.getName()); } private BeanUtils(); static BeanInfo getBeanInfo(Class<?> clazz); static Method getMethod(Class<?> clazz, String name, Class<?>... parameterTypes); static Optional<Method> getMethod(Class<?> clazz, Predicate<Method> predicate); static Stream<Method> getMethods(Class<?> clazz, Predicate<Method> predicate); static Field getDeclaredField(Class<?> clazz, String name); static Field getField(Class<?> clazz, String name); @CheckForNull static Object getValueFromField(Object object, String name); @CheckForNull static Object getValueFromField(Object object, Field field); static String getPropertyName(Method method); static String getPropertyName(Type returnType, String methodName); static final String GET_PREFIX; static final String SET_PREFIX; static final String IS_PREFIX; }### Answer:
@Test public void testGetPropertyName_String_Void() { assertThat(BeanUtils.getPropertyName(Void.TYPE, "getFoo"), is("getFoo")); assertThat(BeanUtils.getPropertyName(Void.TYPE, "isFoo"), is("isFoo")); assertThat(BeanUtils.getPropertyName(Void.TYPE, "foo"), is("foo")); }
@Test public void testGetPropertyName_String_Get() { assertThat(BeanUtils.getPropertyName(String.class, "getFoo"), is("foo")); assertThat(BeanUtils.getPropertyName(Boolean.TYPE, "getFoo"), is("foo")); }
@Test public void testGetPropertyName_String_Is() { assertThat(BeanUtils.getPropertyName(String.class, "isFoo"), is("foo")); assertThat(BeanUtils.getPropertyName(Boolean.TYPE, "isFoo"), is("foo")); }
@Test public void testGetPropertyName_String_FullName() { assertThat(BeanUtils.getPropertyName(String.class, "fooBar"), is("fooBar")); assertThat(BeanUtils.getPropertyName(Boolean.TYPE, "fooBar"), is("fooBar")); } |
### Question:
AbstractPropertyDispatcherDecorator implements PropertyDispatcher { @Override public <T> T pull(Aspect<T> aspect) { return getWrappedDispatcher().pull(aspect); } AbstractPropertyDispatcherDecorator(PropertyDispatcher wrappedDispatcher); @Override Class<?> getValueClass(); @Override MessageList getMessages(MessageList messageList); @Override String getProperty(); @Override @CheckForNull Object getBoundObject(); @Override T pull(Aspect<T> aspect); @Override void push(Aspect<T> aspect); @Override boolean isPushable(Aspect<T> aspect); @Override String toString(); }### Answer:
@Test public void testGetValue() { Aspect<Object> aspect = Aspect.of(""); decorator.pull(aspect); verify(wrappedDispatcher).pull(aspect); } |
### Question:
AbstractPropertyDispatcherDecorator implements PropertyDispatcher { @Override public Class<?> getValueClass() { return wrappedDispatcher.getValueClass(); } AbstractPropertyDispatcherDecorator(PropertyDispatcher wrappedDispatcher); @Override Class<?> getValueClass(); @Override MessageList getMessages(MessageList messageList); @Override String getProperty(); @Override @CheckForNull Object getBoundObject(); @Override T pull(Aspect<T> aspect); @Override void push(Aspect<T> aspect); @Override boolean isPushable(Aspect<T> aspect); @Override String toString(); }### Answer:
@Test public void testGetValueClass() { decorator.getValueClass(); verify(wrappedDispatcher).getValueClass(); } |
### Question:
AbstractPropertyDispatcherDecorator implements PropertyDispatcher { @Override public MessageList getMessages(MessageList messageList) { return getWrappedDispatcher().getMessages(messageList); } AbstractPropertyDispatcherDecorator(PropertyDispatcher wrappedDispatcher); @Override Class<?> getValueClass(); @Override MessageList getMessages(MessageList messageList); @Override String getProperty(); @Override @CheckForNull Object getBoundObject(); @Override T pull(Aspect<T> aspect); @Override void push(Aspect<T> aspect); @Override boolean isPushable(Aspect<T> aspect); @Override String toString(); }### Answer:
@Test public void testMessages() { MessageList messageList = new MessageList(); decorator.getMessages(messageList); verify(wrappedDispatcher).getMessages(messageList); } |
### Question:
AbstractPropertyDispatcherDecorator implements PropertyDispatcher { protected PropertyDispatcher getWrappedDispatcher() { return wrappedDispatcher; } AbstractPropertyDispatcherDecorator(PropertyDispatcher wrappedDispatcher); @Override Class<?> getValueClass(); @Override MessageList getMessages(MessageList messageList); @Override String getProperty(); @Override @CheckForNull Object getBoundObject(); @Override T pull(Aspect<T> aspect); @Override void push(Aspect<T> aspect); @Override boolean isPushable(Aspect<T> aspect); @Override String toString(); }### Answer:
@Test public void testGetWrappedDispatcher() { assertEquals(wrappedDispatcher, decorator.getWrappedDispatcher()); } |
### Question:
ExceptionPropertyDispatcher implements PropertyDispatcher { @Override @CheckForNull public Object getBoundObject() { if (objects.size() > 0) { return objects.get(0); } else { throw new IllegalStateException( "ExceptionPropertyDispatcher has no presentation model object. " + "The bound object should be found in a previous dispatcher in the dispatcher chain before reaching ExceptionPropertyDisptacher."); } } ExceptionPropertyDispatcher(String property, Object... objects); @Override Class<?> getValueClass(); @Override MessageList getMessages(MessageList messageList); @Override String getProperty(); @Override @CheckForNull Object getBoundObject(); @Override T pull(Aspect<T> aspect); @Override void push(Aspect<T> aspect); static String missingMethodMessage(String methodSignature, List<Object> objects); @Override boolean isPushable(Aspect<T> aspect); @Override String toString(); }### Answer:
@Test public void testGetBoundObject() { assertThat(dispatcher.getBoundObject(), is(OBJ1)); } |
### Question:
ExceptionPropertyDispatcher implements PropertyDispatcher { @Override public String toString() { return getClass().getSimpleName() + "[" + objects.stream().map((Object c) -> (c != null) ? c.getClass().getSimpleName() : "null") .collect(joining(",")) + "#" + getProperty() + "]"; } ExceptionPropertyDispatcher(String property, Object... objects); @Override Class<?> getValueClass(); @Override MessageList getMessages(MessageList messageList); @Override String getProperty(); @Override @CheckForNull Object getBoundObject(); @Override T pull(Aspect<T> aspect); @Override void push(Aspect<T> aspect); static String missingMethodMessage(String methodSignature, List<Object> objects); @Override boolean isPushable(Aspect<T> aspect); @Override String toString(); }### Answer:
@Test public void testToString_WithoutNull() { assertThat(dispatcher.toString(), is("ExceptionPropertyDispatcher[String,TestUiComponent#" + PROPERTY_NAME + "]")); }
@Test public void testToString_WithNull() { dispatcher = new ExceptionPropertyDispatcher(PROPERTY_NAME, (String)null); assertThat(dispatcher.toString(), is("ExceptionPropertyDispatcher[null" + "#" + PROPERTY_NAME + "]")); } |
### Question:
ExceptionPropertyDispatcher implements PropertyDispatcher { @Override public MessageList getMessages(MessageList messageList) { return new MessageList(); } ExceptionPropertyDispatcher(String property, Object... objects); @Override Class<?> getValueClass(); @Override MessageList getMessages(MessageList messageList); @Override String getProperty(); @Override @CheckForNull Object getBoundObject(); @Override T pull(Aspect<T> aspect); @Override void push(Aspect<T> aspect); static String missingMethodMessage(String methodSignature, List<Object> objects); @Override boolean isPushable(Aspect<T> aspect); @Override String toString(); }### Answer:
@Test public void testGetMessages() { assertThat(dispatcher.getMessages(new MessageList()).isEmpty(), is(true)); } |
### Question:
ExceptionPropertyDispatcher implements PropertyDispatcher { @Override public <T> boolean isPushable(Aspect<T> aspect) { return false; } ExceptionPropertyDispatcher(String property, Object... objects); @Override Class<?> getValueClass(); @Override MessageList getMessages(MessageList messageList); @Override String getProperty(); @Override @CheckForNull Object getBoundObject(); @Override T pull(Aspect<T> aspect); @Override void push(Aspect<T> aspect); static String missingMethodMessage(String methodSignature, List<Object> objects); @Override boolean isPushable(Aspect<T> aspect); @Override String toString(); }### Answer:
@Test public void testIsPushable() { assertThat(dispatcher.isPushable(Aspect.of(PROPERTY_NAME)), is(false)); } |
### Question:
ExceptionPropertyDispatcher implements PropertyDispatcher { @Override public Class<?> getValueClass() { throw new IllegalStateException( missingMethodMessage("is/get" + StringUtils.capitalize(getProperty()), objects)); } ExceptionPropertyDispatcher(String property, Object... objects); @Override Class<?> getValueClass(); @Override MessageList getMessages(MessageList messageList); @Override String getProperty(); @Override @CheckForNull Object getBoundObject(); @Override T pull(Aspect<T> aspect); @Override void push(Aspect<T> aspect); static String missingMethodMessage(String methodSignature, List<Object> objects); @Override boolean isPushable(Aspect<T> aspect); @Override String toString(); }### Answer:
@Test public void testGetValueClass() { IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, dispatcher::getValueClass); assertThat(illegalStateException.getMessage(), containsStringIgnoringCase(PROPERTY_NAME)); assertThat(illegalStateException.getMessage(), not(containsStringIgnoringCase("object must not be null"))); } |
### Question:
StaticValueDispatcher extends AbstractPropertyDispatcherDecorator { @SuppressWarnings("unchecked") @Override public <T> T pull(Aspect<T> aspect) { if (aspect.isValuePresent()) { T staticValue = aspect.getValue(); Object boundObject = getBoundObject(); if (staticValue instanceof String && boundObject != null) { Class<?> pmoClass = getTypeForKey(boundObject); staticValue = (T)PmoNlsService.get() .getLabel(pmoClass, getProperty(), aspect.getName(), (String)staticValue); } if (LinkkiAspectDefinition.DERIVED_BY_LINKKI.equals(staticValue)) { return (T)StringUtils.capitalize(getProperty()); } return staticValue; } else { return super.pull(aspect); } } StaticValueDispatcher(PropertyDispatcher wrappedDispatcher); @SuppressWarnings("unchecked") @Override T pull(Aspect<T> aspect); }### Answer:
@Test public void testGetValue() { Aspect<Object> newDynamic = Aspect.of(""); pull(XYZ, newDynamic); verify(uiAnnotationFallbackDispatcher).pull(newDynamic); }
@Test public void testGetDerivedValue() { Aspect<String> derived = Aspect.of("", LinkkiAspectDefinition.DERIVED_BY_LINKKI); when(uiAnnotationFallbackDispatcher.getProperty()).thenReturn("foo"); assertThat(pull("foo", derived), is("Foo")); }
@Test public void testPull_static() { Aspect<ArrayList<Object>> staticAspect = Aspect.of(EnabledAspectDefinition.NAME, new ArrayList<>()); pull(STATIC_ENUM_ATTR, staticAspect); verify(uiAnnotationFallbackDispatcher, never()).pull(staticAspect); }
@Test public void testPull_dynamic() { Aspect<ArrayList<Object>> dynamicAspect = Aspect.of(EnabledAspectDefinition.NAME); pull(DYNAMIC_ENUM_ATTR, dynamicAspect); verify(uiAnnotationFallbackDispatcher).pull(dynamicAspect); } |
### Question:
BindingContext implements UiUpdateObserver { @Deprecated public BindingContext add(Binding binding) { add(binding, UiFramework.getComponentWrapperFactory().createComponentWrapper(binding.getBoundComponent())); return this; } BindingContext(); BindingContext(String contextName); BindingContext(String contextName, PropertyBehaviorProvider behaviorProvider,
Handler afterUpdateHandler); BindingContext(String contextName, PropertyBehaviorProvider behaviorProvider,
PropertyDispatcherFactory dispatcherFactory, Handler afterUpdateHandler); String getName(); @Deprecated BindingContext add(Binding binding); BindingContext add(Binding binding, ComponentWrapper componentWrapper); Collection<Binding> getBindings(); void removeBindingsForComponent(Object uiComponent); void removeBindingsForPmo(Object pmo); @Deprecated void updateUI(); void modelChanged(); @Override void uiUpdated(); @Deprecated final void updateMessages(MessageList messages); MessageList displayMessages(MessageList messages); PropertyBehaviorProvider getBehaviorProvider(); @Override String toString(); Binding bind(Object pmo,
BindingDescriptor bindingDescriptor,
ComponentWrapper componentWrapper); Binding bind(Object pmo,
BoundProperty boundProperty,
List<LinkkiAspectDefinition> aspectDefs,
ComponentWrapper componentWrapper); ContainerBinding bindContainer(Object pmo,
BoundProperty boundProperty,
List<LinkkiAspectDefinition> aspectDefs,
ComponentWrapper componentWrapper); @Deprecated final PropertyDispatcher createDispatcherChain(Object pmo,
BindingDescriptor bindingDescriptor); }### Answer:
@Test public void testAdd() { BindingContext context = new BindingContext(); ElementBinding binding = createBinding(context); assertEquals(0, context.getBindings().size()); context.add(binding, TestComponentWrapper.with(binding)); assertEquals(1, context.getBindings().size()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.