method2testcases
stringlengths 118
6.63k
|
---|
### 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:
ApplicableTypeAspectDefinition extends ApplicableAspectDefinition { public static ApplicableTypeAspectDefinition ifComponentTypeIs(Class<?> applicableType, LinkkiAspectDefinition wrappedAspectDefinition) { return new ApplicableTypeAspectDefinition(wrappedAspectDefinition, applicableType); } private ApplicableTypeAspectDefinition(LinkkiAspectDefinition wrappedAspectDefinition, Class<?> applicableType); static ApplicableTypeAspectDefinition ifComponentTypeIs(Class<?> applicableType,
LinkkiAspectDefinition wrappedAspectDefinition); }### Answer:
@Test public final void testCreateUiUpdater() { ApplicableTypeAspectDefinition aspectDef = ApplicableTypeAspectDefinition .ifComponentTypeIs(TestUiComponent.class, aspectDefinition); when(aspectDefinition.createUiUpdater(propertyDispatcher, componentWrapper)).thenReturn(modelUpdated); Handler uiUpdater = aspectDef.createUiUpdater(propertyDispatcher, componentWrapper); verify(aspectDefinition).createUiUpdater(propertyDispatcher, componentWrapper); assertThat(uiUpdater, is(modelUpdated)); }
@Test public final void testCreateUiUpdater_NotApplicable() { ApplicableTypeAspectDefinition aspectDef = ApplicableTypeAspectDefinition.ifComponentTypeIs(String.class, aspectDefinition); aspectDef.createUiUpdater(propertyDispatcher, componentWrapper); verify(aspectDefinition, never()).createUiUpdater(any(PropertyDispatcher.class), any(ComponentWrapper.class)); }
@Test public final void testInitModelUpdate() { ApplicableTypeAspectDefinition aspectDef = ApplicableTypeAspectDefinition .ifComponentTypeIs(TestUiComponent.class, aspectDefinition); aspectDef.initModelUpdate(propertyDispatcher, componentWrapper, modelUpdated); verify(aspectDefinition).initModelUpdate(propertyDispatcher, componentWrapper, modelUpdated); }
@Test public final void testInitModelUpdate_NotApplicable() { ApplicableTypeAspectDefinition aspectDef = ApplicableTypeAspectDefinition.ifComponentTypeIs(List.class, aspectDefinition); aspectDef.initModelUpdate(propertyDispatcher, componentWrapper, modelUpdated); verify(aspectDefinition, never()).initModelUpdate(any(PropertyDispatcher.class), any(ComponentWrapper.class), any(Handler.class)); } |
### Question:
Binder { public void setupBindings(BindingContext bindingContext) { addFieldBindings(bindingContext); addMethodBindings(bindingContext); } Binder(Object view, Object pmo); void setupBindings(BindingContext bindingContext); }### Answer:
@Test public void testSetupBindings() { TestView view = new TestView(); TestPmo pmo = new TestPmo(); Binder binder = new Binder(view, pmo); binder.setupBindings(bindingContext); assertThat(pmo.getClickCount(), is(0)); assertThat(pmo.getModel().getClickCount(), is(0)); assertThat(bindingContext.getBindings(), hasSize(2)); assertThat(view.fieldForFieldBinding.getLabelText(), is("")); assertThat(view.fieldForFieldBinding.isEnabled(), is(true)); assertThat(view.fieldForMethodBinding.getLabelText(), is("mod")); assertThat(view.fieldForMethodBinding.isEnabled(), is(false)); assertThat(view.fieldForFieldBinding.getTooltipText(), is(TestPmo.PMO_ATTRIBUTE_TOOLTIP)); assertThat(view.fieldForMethodBinding.getTooltipText(), is(TestPmo.MODEL_ATTRIBUTE_TOOLTIP)); pmo.setModelAttributeEnabled(true); pmo.setModelAttributeTooltip(TestPmo.PMO_ATTRIBUTE_TOOLTIP); bindingContext.modelChanged(); assertThat(view.fieldForMethodBinding.isEnabled(), is(true)); assertThat(view.fieldForMethodBinding.getTooltipText(), is(TestPmo.PMO_ATTRIBUTE_TOOLTIP)); view.fieldForMethodBinding.setEnabled(false); view.fieldForFieldBinding.click(); view.fieldForMethodBinding.click(); view.fieldForMethodBinding.click(); assertThat(pmo.isModelAttributeEnabled(), is(true)); assertThat(pmo.getClickCount(), is(1)); assertThat(pmo.getModel().getClickCount(), is(2)); }
@Test public void testSetupBindings_ThrowsExceptionForNullField() { TestView view = new TestView(); view.fieldForFieldBinding = null; assertThat(view.fieldForFieldBinding, is(nullValue())); Binder binder = new Binder(view, new TestPmo()); Assertions.assertThrows(NullPointerException.class, () -> { binder.setupBindings(bindingContext); }); }
@Test public void testSetupBindings_ThrowsExceptionForMethodReturningNull() { TestView view = new TestView(); view.fieldForMethodBinding = null; assertThat(view.methodForMethodBinding(), is(nullValue())); Binder binder = new Binder(view, new TestPmo()); Assertions.assertThrows(NullPointerException.class, () -> { binder.setupBindings(bindingContext); }); }
@Test public void testSetupBindings_ThrowsExceptionForAnnotatedNonComponentField() { IllegalFieldAnnotationView view = new IllegalFieldAnnotationView(); Binder binder = new Binder(view, new TestPmo()); Assertions.assertThrows(IllegalStateException.class, () -> { binder.setupBindings(bindingContext); }); }
@Test public void testSetupBindings_ThrowsExceptionForAnnotatedMethodWithParameters() { IllegalMethodParamtersView view = new IllegalMethodParamtersView(); Binder binder = new Binder(view, new TestPmo()); Assertions.assertThrows(IllegalArgumentException.class, () -> { binder.setupBindings(bindingContext); }); }
@Test public void testSetupBindings_ThrowsExceptionForAnnotatedMethodWithNonComponentReturnType() { IllegalMethodReturnTypeView view = new IllegalMethodReturnTypeView(); Binder binder = new Binder(view, new TestPmo()); Assertions.assertThrows(IllegalStateException.class, () -> { binder.setupBindings(bindingContext); }); } |
### Question:
BeanUtils { public static Method getMethod(Class<?> clazz, String name, Class<?>... parameterTypes) { try { return clazz.getMethod(name, parameterTypes); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(e); } catch (SecurityException e) { throw new IllegalStateException(e); } } 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 testGetMethod_PublicMethodIsFound() { Optional<Method> method = BeanUtils.getMethod(Foo.class, (m) -> m.getName().equals("foo")); assertThat(method, is(present())); }
@Test public void testGetMethod_InterfaceMethodIsFound() { Optional<Method> method = BeanUtils.getMethod(Foo.class, (m) -> m.getName().equals("iFoo")); assertThat(method, is(present())); }
@Test public void testGetMethod_SuperTypeMethodIsFound() { Optional<Method> method = BeanUtils.getMethod(Foo.class, (m) -> m.getName().equals("superFoo")); assertThat(method, is(present())); }
@Test public void testGetMethod_PrivateMethodIsFound() { Optional<Method> method = BeanUtils.getMethod(Foo.class, (m) -> m.getName().equals("bar")); assertThat(method, is(present())); }
@Test public void testGetMethod_OneMatchingMethodIsFound() { Assertions.assertThrows(IllegalStateException.class, () -> { BeanUtils.getMethod(Foo.class, (m) -> m.getName().equals("baz")); }); }
@Test public void testGetMethod_NoMethodIsFound() { Optional<Method> method = BeanUtils.getMethod(Foo.class, (m) -> m.getName().equals("hammaned")); assertThat(method, is(not(present()))); } |
### 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 V getPropertyValue(T boundObject) { return readMethod.readValue(boundObject); } 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 testRead() { String propertyValue = stringAccessor.getPropertyValue(testObject); assertEquals(STRING_PROPERTY_INITIAL_VALUE, propertyValue); }
@Test public void testLongProperty() { PropertyAccessor<TestObject, Long> propertyAccessor = new PropertyAccessor<>(TestObject.class, TestObject.READ_ONLY_LONG_PROPERTY); Long propertyValue = propertyAccessor.getPropertyValue(testObject); assertEquals(42, propertyValue.longValue()); }
@Test public void testDefaultMethod() { PropertyAccessor<TestInterface, String> propertyAccessor = new PropertyAccessor<>(TestInterfaceImpl.class, TestInterface.RO_DEFAULT_METHOD); TestInterface testInterfaceImpl = new TestInterfaceImpl(); String propertyValue = propertyAccessor.getPropertyValue(testInterfaceImpl); assertEquals("Hello", propertyValue); }
@Test public void testDefaultMethod_InSubclass() { PropertyAccessor<TestInterface, String> propertyAccessor = new PropertyAccessor<>( TestInterfaceImplSub.class, TestInterface.RO_DEFAULT_METHOD); TestInterface testInterfaceImpl = new TestInterfaceImplSub(); String propertyValue = propertyAccessor.getPropertyValue(testInterfaceImpl); assertEquals("Hello", propertyValue); }
@Test public void testDefaultMethod_OverwrittenInSubclass() { PropertyAccessor<TestInterface, String> propertyAccessor = new PropertyAccessor<>( TestInterfaceOverwriting.class, TestInterface.RO_DEFAULT_METHOD); TestInterface testInterfaceImpl = new TestInterfaceOverwriting(); String propertyValue = propertyAccessor.getPropertyValue(testInterfaceImpl); assertEquals("Hi", propertyValue); }
@Test public void testDefaultMethod_OtherPackage() { PropertyAccessor<TestInterface, String> propertyAccessor = new PropertyAccessor<>( OtherPackageTestObject.class, TestInterface.RO_DEFAULT_METHOD); TestInterface testInterfaceImpl = new OtherPackageTestObject(); String propertyValue = propertyAccessor.getPropertyValue(testInterfaceImpl); assertEquals("other", propertyValue); }
@Test public void testDefaultMethod_OtherPackagePrivate() { TestInterface testInterfaceImpl = OtherPackageTestObject.getPackagePrivateInstance(); PropertyAccessor<TestInterface, String> propertyAccessor = new PropertyAccessor<>( testInterfaceImpl.getClass(), TestInterface.RO_DEFAULT_METHOD); String propertyValue = propertyAccessor.getPropertyValue(testInterfaceImpl); assertEquals("otherPackage", propertyValue); }
@Test public void testDefaultMethod_OtherPackageProtected() { PropertyAccessor<TestPublicSubclass, Integer> propertyAccessor = new PropertyAccessor<>( TestPublicSubclass.class, TestPublicSubclass.PROPERTY_ANSWER); int propertyValue = propertyAccessor.getPropertyValue(new TestPublicSubclass()); assertEquals(42, propertyValue); } |
### 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:
ReflectionPropertyDispatcher implements PropertyDispatcher { @Override public MessageList getMessages(MessageList messageList) { Object boundObject = getBoundObject(); if (boundObject == null) { return new MessageList(); } else { MessageList msgListForBoundObject = messageList.getMessagesFor(boundObject, getProperty()); msgListForBoundObject.add(fallbackDispatcher.getMessages(messageList)); return msgListForBoundObject; } } 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 testGetMessages_Empty() { MessageList messageList = new MessageList(); assertThat(setupPmoDispatcher(XYZ).getMessages(messageList), emptyMessageList()); assertThat(setupPmoDispatcher("invalidProperty").getMessages(messageList), emptyMessageList()); }
@Test public void testGetMessages_ShouldReturnMessagesFromModelObject() { MessageList messageList = new MessageList(); Message msg1 = Message.builder(ABC, Severity.ERROR).invalidObjectWithProperties(testModelObject, XYZ) .create(); Message msg2 = Message.builder(ABC, Severity.ERROR).invalidObjectWithProperties(testModelObject, ABC) .create(); messageList.add(msg1); messageList.add(msg2); assertThat(setupPmoDispatcher(XYZ).getMessages(messageList), hasSize(1)); assertThat(setupPmoDispatcher(ABC).getMessages(messageList), hasSize(1)); assertThat(setupPmoDispatcher("invalidProperty").getMessages(messageList), emptyMessageList()); }
@Test public void testGetMessages_ShouldReturnMessagesFromPmo() { MessageList messageList = new MessageList(); Message msg1 = Message.builder(ABC, Severity.ERROR).invalidObjectWithProperties(testPmo, XYZ).create(); Message msg2 = Message.builder(ABC, Severity.ERROR).invalidObjectWithProperties(testPmo, ABC).create(); Message msg3 = Message.builder(ABC, Severity.ERROR).invalidObjectWithProperties(testModelObject, XYZ) .create(); messageList.add(msg1); messageList.add(msg2); messageList.add(msg3); assertThat(setupPmoDispatcher(XYZ).getMessages(messageList), hasSize(2)); assertThat(setupPmoDispatcher(ABC).getMessages(messageList), hasSize(1)); assertThat(setupPmoDispatcher("invalidProperty").getMessages(messageList), emptyMessageList()); }
@Test public void testGetMessages_IgnoreIrrelevantMessages() { MessageList messageList = new MessageList(); Message msg1 = Message.builder(ABC, Severity.ERROR).invalidObjectWithProperties(new Object(), XYZ).create(); Message msg2 = Message.builder(ABC, Severity.ERROR).invalidObjectWithProperties(new Object(), ABC).create(); messageList.add(msg1); messageList.add(msg2); assertThat(setupPmoDispatcher(XYZ).getMessages(messageList), emptyMessageList()); assertThat(setupPmoDispatcher(ABC).getMessages(messageList), emptyMessageList()); assertThat(setupPmoDispatcher("invalidProperty").getMessages(messageList), emptyMessageList()); } |
### Question:
ReflectionPropertyDispatcher implements PropertyDispatcher { @Override public <V> void push(Aspect<V> aspect) { @CheckForNull Object boundObject = getBoundObject(); if (boundObject != null) { if (aspect.isValuePresent()) { callSetter(aspect); } else { invoke(aspect); } } } 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 testPush_Static() { TestModelObject spyObject = spy(new TestModelObject()); ReflectionPropertyDispatcher dispatcher = new ReflectionPropertyDispatcher(() -> spyObject, TestModelObject.PROPERTY_ABC, new ExceptionPropertyDispatcher(TestModelObject.PROPERTY_ABC)); dispatcher.push(Aspect.of("", "something")); verify(spyObject).setAbc(Mockito.eq("something")); }
@Test public void testPush_Static_PmoWithoutReadMethod() { PropertyDispatcher mockedDispatcher = noActionInPushMockedDispatcher(); ReflectionPropertyDispatcher dispatcher = new ReflectionPropertyDispatcher(this::getTestPmo, TestPMO.INVALID_PROPERTY_MISSING_GETTER_PMO, mockedDispatcher); dispatcher.push(Aspect.of("", "something")); verify(mockedDispatcher, times(1)).push(ArgumentMatchers.<Aspect<?>> any()); }
@Test public void testPush_Static_PmoWithoutWriteMethod() { ReflectionPropertyDispatcher dispatcher = new ReflectionPropertyDispatcher(this::getTestPmo, TestPMO.PROPERTY_PMO_GETTER_ONLY, noActionInPushMockedDispatcher()); Assertions.assertThrows(IllegalArgumentException.class, () -> { dispatcher.push(Aspect.of("", "something")); }); }
@Test public void testPush_Dynamic() { TestPMO spyPmo = spy(testPmo); ReflectionPropertyDispatcher dispatcher = new ReflectionPropertyDispatcher(() -> spyPmo, TestPMO.PROPERTY_BUTTON_CLICK, new ExceptionPropertyDispatcher(TestPMO.PROPERTY_BUTTON_CLICK)); dispatcher.push(Aspect.of("")); verify(spyPmo).buttonClick(); }
@Test public void testPush_Dynamic_NoBoundObject() { TestPMO spyPmo = spy(testPmo); ReflectionPropertyDispatcher dispatcher = new ReflectionPropertyDispatcher(() -> null, TestPMO.PROPERTY_BUTTON_CLICK, new ExceptionPropertyDispatcher(TestPMO.PROPERTY_BUTTON_CLICK)); dispatcher.push(Aspect.of("")); verify(spyPmo, never()).buttonClick(); }
@Test public void testPush_Dynamic_NoMethod() { TestPMO spyPmo = spy(testPmo); ReflectionPropertyDispatcher dispatcher = new ReflectionPropertyDispatcher(() -> spyPmo, TestPMO.PROPERTY_BUTTON_CLICK, new ExceptionPropertyDispatcher(TestPMO.PROPERTY_BUTTON_CLICK)); Assertions.assertThrows(IllegalArgumentException.class, () -> { dispatcher.push(Aspect.of("NoMethod")); }); } |
### Question:
ReflectionPropertyDispatcher implements PropertyDispatcher { @Override public <V> boolean isPushable(Aspect<V> aspect) { @CheckForNull Object boundObject = getBoundObject(); if (boundObject == null) { return fallbackDispatcher.isPushable(aspect); } String propertyAspectName = getPropertyAspectName(aspect); if (aspect.isValuePresent()) { return (hasReadMethod(propertyAspectName) && hasWriteMethod(propertyAspectName)) || (!hasReadMethod(propertyAspectName) && fallbackDispatcher.isPushable(aspect)); } else { return hasInvokeMethod(propertyAspectName) || fallbackDispatcher.isPushable(aspect); } } 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 testIsPushable_WithReadWithoutWrite() { ReflectionPropertyDispatcher dispatcher = new ReflectionPropertyDispatcher(this::getTestPmo, TestPMO.PROPERTY_PMO_GETTER_ONLY, new ExceptionPropertyDispatcher(TestPMO.PROPERTY_PMO_GETTER_ONLY)); assertThat(dispatcher.isPushable(Aspect.of("", "something")), is(false)); }
@Test public void testIsPushable_WithReadAndWrite() { ReflectionPropertyDispatcher dispatcher = new ReflectionPropertyDispatcher(this::getTestPmo, TestPMO.PROPERTY_PMO_PROP, new ExceptionPropertyDispatcher(TestPMO.PROPERTY_PMO_PROP)); assertThat(dispatcher.isPushable(Aspect.of("", "something")), is(true)); }
@Test public void testIsPushable_WithReadAndWriteNoBoundObject() { ReflectionPropertyDispatcher dispatcher = new ReflectionPropertyDispatcher(() -> null, TestPMO.PROPERTY_PMO_PROP, new ExceptionPropertyDispatcher(TestPMO.PROPERTY_PMO_PROP)); assertThat(dispatcher.isPushable(Aspect.of("", "something")), is(false)); }
@Test public void testIsPushable_NoInvokeMethod() { ReflectionPropertyDispatcher dispatcher = new ReflectionPropertyDispatcher(this::getTestPmo, TestPMO.PROPERTY_PMO_GETTER_ONLY, new ExceptionPropertyDispatcher(TestPMO.PROPERTY_PMO_GETTER_ONLY)); assertThat(dispatcher.isPushable(Aspect.of("")), is(false)); }
@Test public void testIsPushable_InvokeMethod() { ReflectionPropertyDispatcher dispatcher = new ReflectionPropertyDispatcher(this::getTestPmo, TestPMO.PROPERTY_BUTTON_CLICK, new ExceptionPropertyDispatcher(TestPMO.PROPERTY_BUTTON_CLICK)); assertThat(dispatcher.isPushable(Aspect.of("")), is(true)); }
@Test public void testIsPushable_InvokeMethodNoBoundObject() { ReflectionPropertyDispatcher dispatcher = new ReflectionPropertyDispatcher(() -> null, TestPMO.PROPERTY_BUTTON_CLICK, new ExceptionPropertyDispatcher(TestPMO.PROPERTY_BUTTON_CLICK)); assertThat(dispatcher.isPushable(Aspect.of("")), is(false)); } |
### 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()); } |
### Question:
BindingContext implements UiUpdateObserver { public void modelChanged() { updateUI(); } 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 testModelChangedBindingsAndValidate_noBindingInContext() { Handler afterUpdateUi = mock(Handler.class); BindingContext context = new BindingContext("", PropertyBehaviorProvider.NO_BEHAVIOR_PROVIDER, afterUpdateUi); context.modelChanged(); verify(afterUpdateUi).apply(); } |
### Question:
BindingContext implements UiUpdateObserver { public void removeBindingsForComponent(Object uiComponent) { bindings.remove(uiComponent); UiFramework.getChildComponents(uiComponent) .iterator() .forEachRemaining(this::removeBindingsForComponent); getBindingStream() .filter(BindingContext.class::isInstance) .map(BindingContext.class::cast) .forEach(bc -> bc.removeBindingsForComponent(uiComponent)); } 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 testRemoveBindingsForComponent() { BindingContext context = new BindingContext(); TestPmo testPmo = new TestPmo(); ElementBinding binding1 = createBinding(context, testPmo, field1); ElementBinding binding2 = createBinding(context, testPmo, field2); context.add(binding1, TestComponentWrapper.with(binding1)); context.add(binding2, TestComponentWrapper.with(binding2)); assertThat(context.getBindings(), hasSize(2)); TestUiLayoutComponent layout = new TestUiLayoutComponent(field1, field2); context.removeBindingsForComponent(layout); assertThat(context.getBindings(), is(empty())); } |
### Question:
BindingContext implements UiUpdateObserver { public void removeBindingsForPmo(Object pmo) { bindings.values().removeIf(ref -> { Binding binding = ref.get(); return binding != null && binding.getPmo() == pmo; }); getBindingStream() .filter(BindingContext.class::isInstance) .map(BindingContext.class::cast) .forEach(bc -> bc.removeBindingsForPmo(pmo)); if (pmo instanceof PresentationModelObject) { ((PresentationModelObject)pmo).getEditButtonPmo().ifPresent(this::removeBindingsForPmo); } if (pmo instanceof ContainerPmo) { ((ContainerPmo<?>)pmo).getAddItemButtonPmo().ifPresent(this::removeBindingsForPmo); } } 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 testRemoveBindingsForPmo() { BindingContext context = new BindingContext(); TestPmo pmo = new TestPmo(); ElementBinding binding1 = createBinding(context, pmo, field1); ElementBinding binding2 = createBinding(context, pmo, field2); context.add(binding1, TestComponentWrapper.with(binding1)); context.add(binding2, TestComponentWrapper.with(binding2)); assertThat(context.getBindings(), hasSize(2)); context.removeBindingsForPmo(pmo); assertThat(context.getBindings(), is(empty())); } |
### Question:
BindingContext implements UiUpdateObserver { public Binding bind(Object pmo, BindingDescriptor bindingDescriptor, ComponentWrapper componentWrapper) { requireNonNull(bindingDescriptor, "bindingDescriptor must not be null"); return bind(pmo, bindingDescriptor.getBoundProperty(), bindingDescriptor.getAspectDefinitions(), componentWrapper); } 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 testBind_ButtonPmoBindningToCheckUpdateFromPmo() { BindingContext context = new BindingContext(); TestButtonPmo buttonPmo = new TestButtonPmo(); TestUiComponent button = new TestUiComponent(); buttonPmo.setEnabled(false); ComponentWrapper buttonWrapper = new TestComponentWrapper(button); context.bind(buttonPmo, BoundProperty.of(""), Arrays.asList(new EnabledAspectDefinition(EnabledType.DYNAMIC)), buttonWrapper); assertThat(button.isEnabled(), is(false)); } |
### Question:
BindingContext implements UiUpdateObserver { public Collection<Binding> getBindings() { return Collections.unmodifiableCollection(getBindingStream() .collect(toList())); } 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 testBind_WeakReferencedBinding() { BindingContext context = new BindingContext(); ReferenceQueue<TestUiComponent> referenceQueue = new ReferenceQueue<>(); Thread refRemoveThread = new Thread(() -> { try { TestUiComponent removed = referenceQueue.remove(10_000).get(); assertThat(weakRefComponent.get(), is(removed)); } catch (IllegalArgumentException | InterruptedException e) { throw new RuntimeException(e); } }); refRemoveThread.start(); weakRefComponent = setupBindingForWeakRefTest(context, referenceQueue); System.gc(); try { refRemoveThread.join(10_000); } catch (InterruptedException e) { fail(e); } assertThat(context.getBindings(), is(empty())); } |
### Question:
WrapperType { public boolean isAssignableFrom(@CheckForNull WrapperType type) { return this.equals(type) || (type != null && isAssignableFrom(type.getParent())); } private WrapperType(String name, WrapperType parent); static WrapperType of(String name); static WrapperType of(String name, WrapperType parent); @CheckForNull WrapperType getParent(); boolean isRoot(); boolean isAssignableFrom(@CheckForNull WrapperType type); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final WrapperType ROOT; static final WrapperType COMPONENT; static final WrapperType LAYOUT; static final WrapperType FIELD; }### Answer:
@Test public void testIsAssignableFrom() { assertTrue(WrapperType.ROOT.isAssignableFrom(WrapperType.ROOT)); assertTrue(WrapperType.ROOT.isAssignableFrom(WrapperType.COMPONENT)); assertTrue(WrapperType.ROOT.isAssignableFrom(WrapperType.FIELD)); assertTrue(WrapperType.ROOT.isAssignableFrom(WrapperType.LAYOUT)); assertTrue(WrapperType.ROOT.isAssignableFrom(WrapperType.of("custom"))); assertTrue(WrapperType.ROOT.isAssignableFrom(WrapperType.of("customComponent", WrapperType.COMPONENT))); assertTrue(WrapperType.COMPONENT.isAssignableFrom(WrapperType.COMPONENT)); assertTrue(WrapperType.COMPONENT.isAssignableFrom(WrapperType.LAYOUT)); assertTrue(WrapperType.COMPONENT.isAssignableFrom(WrapperType.FIELD)); assertFalse(WrapperType.FIELD.isAssignableFrom(WrapperType.COMPONENT)); assertFalse(WrapperType.FIELD.isAssignableFrom(WrapperType.ROOT)); assertFalse(WrapperType.of("custom").isAssignableFrom(WrapperType.COMPONENT)); assertFalse(WrapperType.of("custom", WrapperType.COMPONENT).isAssignableFrom(WrapperType.COMPONENT)); } |
### Question:
WrapperType { public boolean isRoot() { return this == ROOT; } private WrapperType(String name, WrapperType parent); static WrapperType of(String name); static WrapperType of(String name, WrapperType parent); @CheckForNull WrapperType getParent(); boolean isRoot(); boolean isAssignableFrom(@CheckForNull WrapperType type); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final WrapperType ROOT; static final WrapperType COMPONENT; static final WrapperType LAYOUT; static final WrapperType FIELD; }### Answer:
@Test public void testIsRoot() { assertTrue(WrapperType.ROOT.isRoot()); assertFalse(WrapperType.COMPONENT.isRoot()); assertFalse(WrapperType.FIELD.isRoot()); assertFalse(WrapperType.of("foo", null).isRoot()); assertFalse(WrapperType.of("", null).isRoot()); } |
### Question:
WrapperType { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } WrapperType other = (WrapperType)obj; if (!name.equals(other.name)) { return false; } if (parent == null) { if (other.parent != null) { return false; } } else if (!parent.equals(other.parent)) { return false; } return true; } private WrapperType(String name, WrapperType parent); static WrapperType of(String name); static WrapperType of(String name, WrapperType parent); @CheckForNull WrapperType getParent(); boolean isRoot(); boolean isAssignableFrom(@CheckForNull WrapperType type); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final WrapperType ROOT; static final WrapperType COMPONENT; static final WrapperType LAYOUT; static final WrapperType FIELD; }### Answer:
@SuppressWarnings("unlikely-arg-type") @Test public void testEquals() { assertTrue(WrapperType.ROOT.equals(WrapperType.ROOT)); assertTrue(WrapperType.ROOT.equals(WrapperType.of("", null))); assertTrue(WrapperType.of("", null).equals(WrapperType.ROOT)); assertFalse(WrapperType.ROOT.equals(WrapperType.COMPONENT)); assertFalse(WrapperType.COMPONENT.equals(WrapperType.ROOT)); assertTrue(WrapperType.COMPONENT.equals(WrapperType.COMPONENT)); assertTrue(WrapperType.COMPONENT.equals(WrapperType.of("component", WrapperType.ROOT))); assertTrue(WrapperType.of("component", WrapperType.ROOT).equals(WrapperType.COMPONENT)); assertFalse(WrapperType.COMPONENT.equals(WrapperType.FIELD)); assertFalse(WrapperType.FIELD.equals(WrapperType.COMPONENT)); assertFalse(WrapperType.FIELD.equals("field")); assertFalse(WrapperType.FIELD.equals(WrapperType.of("field", WrapperType.FIELD))); assertFalse(WrapperType.FIELD.equals(WrapperType.of("field", null))); assertFalse(WrapperType.of("field", null).equals(WrapperType.FIELD)); } |
### Question:
WrapperType { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + name.hashCode(); if (parent != null) { result = parent.hashCode() + result * prime; } return result; } private WrapperType(String name, WrapperType parent); static WrapperType of(String name); static WrapperType of(String name, WrapperType parent); @CheckForNull WrapperType getParent(); boolean isRoot(); boolean isAssignableFrom(@CheckForNull WrapperType type); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final WrapperType ROOT; static final WrapperType COMPONENT; static final WrapperType LAYOUT; static final WrapperType FIELD; }### Answer:
@Test public void testHashcode() { assertThat(WrapperType.ROOT.hashCode(), is(WrapperType.ROOT.hashCode())); assertThat(WrapperType.ROOT.hashCode(), is(WrapperType.of("", null).hashCode())); assertThat(WrapperType.of("", null).hashCode(), is(WrapperType.ROOT.hashCode())); assertThat(WrapperType.ROOT.hashCode(), is(not((WrapperType.COMPONENT.hashCode())))); assertThat(WrapperType.COMPONENT.hashCode(), is(not((WrapperType.ROOT.hashCode())))); assertThat(WrapperType.COMPONENT.hashCode(), is(WrapperType.COMPONENT.hashCode())); assertThat(WrapperType.COMPONENT.hashCode(), is(WrapperType.of("component", WrapperType.ROOT).hashCode())); assertThat(WrapperType.of("component", WrapperType.ROOT).hashCode(), is(WrapperType.COMPONENT.hashCode())); assertThat(WrapperType.COMPONENT.hashCode(), is(not((WrapperType.FIELD.hashCode())))); assertThat(WrapperType.FIELD.hashCode(), is(not((WrapperType.COMPONENT.hashCode())))); assertThat(WrapperType.FIELD.hashCode(), is(not(("field".hashCode())))); assertThat(WrapperType.FIELD.hashCode(), is(not((WrapperType.of("field", WrapperType.FIELD).hashCode())))); assertThat(WrapperType.FIELD.hashCode(), is(not((WrapperType.of("field", null).hashCode())))); assertThat(WrapperType.of("field", null).hashCode(), is(not((WrapperType.FIELD.hashCode())))); } |
### Question:
ElementBinding implements Binding { @Override public void updateFromPmo() { try { aspectUpdaters.updateUI(); componentWrapper.postUpdate(); } catch (RuntimeException e) { throw new LinkkiBindingException( "Error while updating UI (" + e.getMessage() + ") in " + toString(), e); } } ElementBinding(ComponentWrapper componentWrapper, PropertyDispatcher propertyDispatcher,
Handler modelChanged, List<LinkkiAspectDefinition> aspectDefinitions); PropertyDispatcher getPropertyDispatcher(); @Override void updateFromPmo(); @Override Object getBoundComponent(); @Override @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "because that's what requireNonNull is for") Object getPmo(); @Override MessageList displayMessages(MessageList messages); @Override String toString(); }### Answer:
@Test public void testUpdateFromPmo_updateAspect() { Handler componentUpdater = mock(Handler.class); LinkkiAspectDefinition aspectDefinition = mock(LinkkiAspectDefinition.class); when(aspectDefinition.supports(any())).thenReturn(true); when(aspectDefinition.createUiUpdater(any(), any())).thenReturn(componentUpdater); ElementBinding fieldBinding = new ElementBinding(new TestComponentWrapper(field), propertyDispatcherValue, Handler.NOP_HANDLER, Arrays.asList(aspectDefinition)); fieldBinding.updateFromPmo(); verify(componentUpdater).apply(); } |
### Question:
ElementBinding implements Binding { @Override public MessageList displayMessages(MessageList messages) { MessageList messagesForProperty = getRelevantMessages(messages); componentWrapper.setValidationMessages(messagesForProperty); return messagesForProperty; } ElementBinding(ComponentWrapper componentWrapper, PropertyDispatcher propertyDispatcher,
Handler modelChanged, List<LinkkiAspectDefinition> aspectDefinitions); PropertyDispatcher getPropertyDispatcher(); @Override void updateFromPmo(); @Override Object getBoundComponent(); @Override @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "because that's what requireNonNull is for") Object getPmo(); @Override MessageList displayMessages(MessageList messages); @Override String toString(); }### Answer:
@Test public void testDisplayMessages() { messageList.add(Message.newError("code", "text")); selectBinding.displayMessages(messageList); @NonNull MessageList validationMessages = selectField.getValidationMessages(); assertThat(validationMessages, hasErrorMessage("code")); Message firstMessage = validationMessages.getFirstMessage(Severity.ERROR).get(); assertEquals(firstMessage.getText(), "text"); }
@Test public void testDisplayMessages_noMessages() { selectBinding.displayMessages(messageList); assertThat(selectField.getValidationMessages(), is(emptyMessageList())); }
@Test public void testDisplayMessages_noMessageList() { Assertions.assertThrows(NullPointerException.class, () -> { selectBinding.displayMessages(null); }); } |
### Question:
MultiformatDateField extends DateField { public List<String> getAlternativeFormat() { return Arrays.asList(getState().getAlternativeFormats()); } MultiformatDateField(); MultiformatDateField(String caption, LocalDate value); MultiformatDateField(String caption); MultiformatDateField(
ValueChangeListener<LocalDate> valueChangeListener); MultiformatDateField(String caption,
ValueChangeListener<LocalDate> valueChangeListener); MultiformatDateField(String caption, LocalDate value,
ValueChangeListener<LocalDate> valueChangeListener); @Override void setDateFormat(String dateFormat); void setAlternativeFormats(List<String> formats); void addAlternativeFormat(String formatString); List<String> getAlternativeFormat(); }### Answer:
@Test public void testSetDateFormat_NoSpecialDateFormatSet() { MultiformatDateField multiformatDateField = new MultiformatDateField(); String dateFormat = multiformatDateField.getDateFormat(); List<String> alternativeFormat = multiformatDateField.getAlternativeFormat(); assertThat(dateFormat, is(nullValue())); assertThat(alternativeFormat, is(empty())); } |
### Question:
ApplicationLayout extends VerticalLayout implements ViewDisplay { protected <T extends View & Component> T getCurrentView() { @SuppressWarnings("unchecked") T view = (T)mainArea; return view; } ApplicationLayout(ApplicationHeader header, @CheckForNull ApplicationFooter footer); @Override void showView(View view); }### Answer:
@Test public void testGetCurrentView_empty() { setUpApplicationLayout(); Component currentView = applicationLayout.getCurrentView(); assertThat(currentView, is(instanceOf(EmptyView.class))); }
@Test public void testGetCurrentView() { setUpApplicationLayout(); View view = mock(View.class, withSettings().extraInterfaces(Component.class).defaultAnswer(Mockito.CALLS_REAL_METHODS)); applicationLayout.showView(view); Component currentView = applicationLayout.getCurrentView(); assertThat(currentView, is(view)); }
@Test public void testGetCurrentView() { setUpApplicationLayout(); View view = mock(View.class, withSettings().extraInterfaces(Component.class)); applicationLayout.showView(view); Component currentView = applicationLayout.getCurrentView(); assertThat(currentView, is(view)); } |
### Question:
ApplicationLayout extends VerticalLayout implements ViewDisplay { @Override public void showView(View view) { setMainArea(view.getViewComponent()); } ApplicationLayout(ApplicationHeader header, @CheckForNull ApplicationFooter footer); @Override void showView(View view); }### Answer:
@Test public void testShowView() { setUpApplicationLayout(); assertThat(applicationLayout.getComponentCount(), is(3)); assertThat(applicationLayout.getComponent(1), is(instanceOf(EmptyView.class))); View view = mock(View.class, withSettings().extraInterfaces(Component.class).defaultAnswer(Mockito.CALLS_REAL_METHODS)); applicationLayout.showView(view); assertThat(applicationLayout.getComponentCount(), is(3)); assertThat(applicationLayout.getComponent(1), is(view)); View view2 = mock(View.class, withSettings().extraInterfaces(Component.class).defaultAnswer(Mockito.CALLS_REAL_METHODS)); applicationLayout.showView(view2); assertThat(applicationLayout.getComponentCount(), is(3)); assertThat(applicationLayout.getComponent(1), is(view2)); }
@Test public void testShowView_NotAComponent() { setUpApplicationLayout(); assertThat(applicationLayout.getComponentCount(), is(3)); assertThat(applicationLayout.getComponent(1), is(instanceOf(EmptyView.class))); View view = mock(View.class, withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS)); Assertions.assertThrows(IllegalStateException.class, () -> { applicationLayout.showView(view); }); }
@Test public void testShowView_WithViewComponent() { setUpApplicationLayout(); assertThat(applicationLayout.getComponentCount(), is(3)); assertThat(applicationLayout.getComponent(1), is(instanceOf(EmptyView.class))); View view = mock(View.class); Component component = mock(Component.class); when(view.getViewComponent()).thenReturn(component); applicationLayout.showView(view); assertThat(applicationLayout.getComponentCount(), is(3)); assertThat(applicationLayout.getComponent(1), is(component)); }
@Test public void testShowView_NoFooter() { applicationLayout = new ApplicationLayout(header, null); assertThat(applicationLayout.getComponentCount(), is(2)); assertThat(applicationLayout.getComponent(1), is(instanceOf(EmptyView.class))); View view = mock(View.class, withSettings().extraInterfaces(Component.class).defaultAnswer(Mockito.CALLS_REAL_METHODS)); applicationLayout.showView(view); assertThat(applicationLayout.getComponentCount(), is(2)); assertThat(applicationLayout.getComponent(1), is(view)); View view2 = mock(View.class, withSettings().extraInterfaces(Component.class).defaultAnswer(Mockito.CALLS_REAL_METHODS)); applicationLayout.showView(view2); assertThat(applicationLayout.getComponentCount(), is(2)); assertThat(applicationLayout.getComponent(1), is(view2)); } |
### Question:
LinkkiUi extends UI { @Override protected void init(VaadinRequest request) { requireNonNull(applicationConfig, "configure must be called before executing any initialization to set an ApplicationConfig"); ApplicationLayout applicationLayout = applicationConfig.createApplicationLayout(); setContent(applicationLayout); configureNavigator(applicationLayout); configureErrorHandler(); VaadinSession vaadinSession = VaadinSession.getCurrent(); if (vaadinSession != null) { vaadinSession.setAttribute(LinkkiConverterRegistry.class, applicationConfig.getConverterRegistry()); vaadinSession.setErrorHandler(getErrorHandler()); } Page.getCurrent().setTitle(getPageTitle()); } @SuppressFBWarnings(value = "NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "applicationConfig/Layout will be non-null once configure was called") protected LinkkiUi(); @SuppressFBWarnings(value = "NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "applicationConfig/Layout will be non-null once configure was called") LinkkiUi(ApplicationConfig applicationConfig); ApplicationConfig getApplicationConfig(); ApplicationLayout getApplicationLayout(); @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "when called from the constructor before configure") @Override void setContent(@CheckForNull Component content); static LinkkiUi getCurrent(); static ApplicationConfig getCurrentApplicationConfig(); @Deprecated static ApplicationNavigator getCurrentApplicationNavigator(); static Navigator getCurrentNavigator(); static ApplicationLayout getCurrentApplicationLayout(); }### Answer:
@Test public void testInit() { initUi(); assertThat(UI.getCurrent().getContent(), is(linkkiUi.getApplicationLayout())); } |
### Question:
LinkkiUi extends UI { public ApplicationLayout getApplicationLayout() { return (ApplicationLayout)getContent(); } @SuppressFBWarnings(value = "NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "applicationConfig/Layout will be non-null once configure was called") protected LinkkiUi(); @SuppressFBWarnings(value = "NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "applicationConfig/Layout will be non-null once configure was called") LinkkiUi(ApplicationConfig applicationConfig); ApplicationConfig getApplicationConfig(); ApplicationLayout getApplicationLayout(); @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "when called from the constructor before configure") @Override void setContent(@CheckForNull Component content); static LinkkiUi getCurrent(); static ApplicationConfig getCurrentApplicationConfig(); @Deprecated static ApplicationNavigator getCurrentApplicationNavigator(); static Navigator getCurrentNavigator(); static ApplicationLayout getCurrentApplicationLayout(); }### Answer:
@Test public void testLayoutInitializedWithCorrectLocale() { linkkiUi.setLocale(Locale.CANADA); initUi(); String menuItem = ((ApplicationMenu)((ApplicationHeader)linkkiUi.getApplicationLayout().getComponent(0)) .getComponent(0)).getItems().get(0).getText(); assertThat(menuItem, is(Locale.CANADA.getDisplayCountry())); } |
### Question:
DateFormats { public static String getPattern(Locale locale) { requireNonNull(locale, "locale must not be null"); String registeredPattern = LANGUAGE_PATTERNS.get(locale.getLanguage()); if (registeredPattern != null) { return registeredPattern; } else { return defaultLocalePattern(locale); } } private DateFormats(); static void register(String languageCode, String pattern); static String getPattern(Locale locale); static final String PATTERN_ISO; static final String PATTERN_DE; }### Answer:
@Test public void testGetPattern() { assertThat(DateFormats.getPattern(GERMAN), is(DateFormats.PATTERN_DE)); assertThat(DateFormats.getPattern(GERMANY), is(DateFormats.PATTERN_DE)); assertThat(DateFormats.getPattern(AUSTRIA), is(DateFormats.PATTERN_DE)); assertThat(DateFormats.getPattern(ENGLISH), is(not(nullValue()))); assertThat(DateFormats.getPattern(ENGLISH), is(not(DateFormats.PATTERN_DE))); assertThat(DateFormats.getPattern(ENGLISH), is(not(DateFormats.PATTERN_ISO))); assertThat(DateFormats.getPattern(ENGLISH), is("M/d/yy")); assertThat(DateFormats.getPattern(US), is(not(nullValue()))); assertThat(DateFormats.getPattern(US), is(not(DateFormats.PATTERN_DE))); assertThat(DateFormats.getPattern(US), is(not(DateFormats.PATTERN_ISO))); assertThat(DateFormats.getPattern(US), is("M/d/yy")); assertThat(DateFormats.getPattern(UK), is(oneOf("dd/MM/yy", "dd/MM/y"))); } |
### Question:
SidebarSheet { protected void unselect() { getButton().removeStyleName(LinkkiApplicationTheme.SIDEBAR_SELECTED); getContent().setVisible(false); } @Deprecated SidebarSheet(Resource icon, Component content, String tooltip); SidebarSheet(Resource icon, String name, Component content); SidebarSheet(Resource icon, String name, Component content, UiUpdateObserver uiUpdateObserver); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier,
@CheckForNull UiUpdateObserver uiUpdateObserver); SidebarSheet(String id, Resource icon, String name, Component content, UiUpdateObserver uiUpdateObserver); SidebarSheet(String id, Resource icon, String name, Component content); SidebarSheet(String id, Resource icon, String name, Supplier<Component> contentSupplier); SidebarSheet(String id, Resource icon, String name, Supplier<Component> contentSupplier,
@CheckForNull UiUpdateObserver uiUpdateObserver); String getId(); Button getButton(); Component getContent(); String getName(); Optional<UiUpdateObserver> getUiUpdateObserver(); void setUiUpdateObserver(@CheckForNull UiUpdateObserver uiUpdateObserver); @Override String toString(); }### Answer:
@Test public void testUnselect_checkVisibilitySetToFalse() { HorizontalLayout content = new HorizontalLayout(); SidebarSheet sheet = createSideBarSheet(content); sheet.unselect(); assertThat(content.isVisible(), is(false)); } |
### Question:
SidebarSheet { protected void select() { uiUpdateObserver.ifPresent(UiUpdateObserver::uiUpdated); getContent().setVisible(true); getButton().addStyleName(LinkkiApplicationTheme.SIDEBAR_SELECTED); } @Deprecated SidebarSheet(Resource icon, Component content, String tooltip); SidebarSheet(Resource icon, String name, Component content); SidebarSheet(Resource icon, String name, Component content, UiUpdateObserver uiUpdateObserver); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier,
@CheckForNull UiUpdateObserver uiUpdateObserver); SidebarSheet(String id, Resource icon, String name, Component content, UiUpdateObserver uiUpdateObserver); SidebarSheet(String id, Resource icon, String name, Component content); SidebarSheet(String id, Resource icon, String name, Supplier<Component> contentSupplier); SidebarSheet(String id, Resource icon, String name, Supplier<Component> contentSupplier,
@CheckForNull UiUpdateObserver uiUpdateObserver); String getId(); Button getButton(); Component getContent(); String getName(); Optional<UiUpdateObserver> getUiUpdateObserver(); void setUiUpdateObserver(@CheckForNull UiUpdateObserver uiUpdateObserver); @Override String toString(); }### Answer:
@Test public void testSelect_checkVisibilitySetToTrue() { HorizontalLayout content = new HorizontalLayout(); SidebarSheet sheet = createSideBarSheet(content); sheet.select(); assertThat(content.isVisible(), is(true)); }
@Test public void testSelect_CheckObserver() { HorizontalLayout content = new HorizontalLayout(); SidebarSheet sidebarSheet = new SidebarSheet(VaadinIcons.STAR_HALF_LEFT, "Test SidebarSheet", content, () -> triggered = true); sidebarSheet.select(); assertThat(triggered, is(true)); } |
### Question:
SidebarSheet { @Override public String toString() { return name; } @Deprecated SidebarSheet(Resource icon, Component content, String tooltip); SidebarSheet(Resource icon, String name, Component content); SidebarSheet(Resource icon, String name, Component content, UiUpdateObserver uiUpdateObserver); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier,
@CheckForNull UiUpdateObserver uiUpdateObserver); SidebarSheet(String id, Resource icon, String name, Component content, UiUpdateObserver uiUpdateObserver); SidebarSheet(String id, Resource icon, String name, Component content); SidebarSheet(String id, Resource icon, String name, Supplier<Component> contentSupplier); SidebarSheet(String id, Resource icon, String name, Supplier<Component> contentSupplier,
@CheckForNull UiUpdateObserver uiUpdateObserver); String getId(); Button getButton(); Component getContent(); String getName(); Optional<UiUpdateObserver> getUiUpdateObserver(); void setUiUpdateObserver(@CheckForNull UiUpdateObserver uiUpdateObserver); @Override String toString(); }### Answer:
@Test public void testToString() { SidebarSheet sheet = new SidebarSheet(VaadinIcons.ADJUST, "Foo", new TextField()); assertThat(sheet.toString(), is("Foo")); } |
### Question:
SidebarSheet { public String getId() { return id; } @Deprecated SidebarSheet(Resource icon, Component content, String tooltip); SidebarSheet(Resource icon, String name, Component content); SidebarSheet(Resource icon, String name, Component content, UiUpdateObserver uiUpdateObserver); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier); SidebarSheet(Resource icon, String name, Supplier<Component> contentSupplier,
@CheckForNull UiUpdateObserver uiUpdateObserver); SidebarSheet(String id, Resource icon, String name, Component content, UiUpdateObserver uiUpdateObserver); SidebarSheet(String id, Resource icon, String name, Component content); SidebarSheet(String id, Resource icon, String name, Supplier<Component> contentSupplier); SidebarSheet(String id, Resource icon, String name, Supplier<Component> contentSupplier,
@CheckForNull UiUpdateObserver uiUpdateObserver); String getId(); Button getButton(); Component getContent(); String getName(); Optional<UiUpdateObserver> getUiUpdateObserver(); void setUiUpdateObserver(@CheckForNull UiUpdateObserver uiUpdateObserver); @Override String toString(); }### Answer:
@Test public void testGetId_DerivedByName() { SidebarSheet sidebarSheet = new SidebarSheet(VaadinIcons.STAR_HALF_LEFT, "Test SidebarSheet", new HorizontalLayout()); assertThat(sidebarSheet.getId(), is("Test SidebarSheet")); }
@Test public void testGetId() { SidebarSheet sidebarSheet = new SidebarSheet("sheet1", VaadinIcons.STAR_HALF_LEFT, "Test SidebarSheet", new HorizontalLayout()); assertThat(sidebarSheet.getId(), is("sheet1")); } |
### Question:
SidebarLayout extends CssLayout { public void select(String id) { getSidebarSheet(id).ifPresent(this::select); } SidebarLayout(); void addSheets(Stream<SidebarSheet> sheets); void addSheets(Iterable<SidebarSheet> sheets); void addSheets(@NonNull SidebarSheet... sheets); void addSheet(SidebarSheet sheet); Registration addSelectionListener(SelectionListener listener); void select(String id); void select(SidebarSheet sheet); SidebarSheet getSelected(); List<SidebarSheet> getSidebarSheets(); Optional<SidebarSheet> getSidebarSheet(String id); }### Answer:
@Test public void testSelect_NotRegistered() { SidebarLayout sidebarLayout = new SidebarLayout(); SidebarSheet sheet1 = new SidebarSheet(ANY_ICON, ANY_STRING, createNewContent()); Assertions.assertThrows(IllegalArgumentException.class, () -> { sidebarLayout.select(sheet1); }); } |
### Question:
OkCancelDialog extends Window { public static Builder builder(String caption) { return new Builder(caption); } protected OkCancelDialog(String caption, Handler okHandler, Handler cancelHandler,
ButtonOption buttonOption, Component... contentComponents); @Deprecated OkCancelDialog(String caption); @Deprecated OkCancelDialog(String caption, Handler okHandler); @Deprecated OkCancelDialog(String caption, Handler okHandler, ButtonOption buttonOption); @Deprecated OkCancelDialog(String caption, Component content, Handler okHandler, ButtonOption buttonOption); @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "yeah, we know...") @Override void setContent(@CheckForNull Component content); void setSize(String width, String height); MessageList validate(); ValidationService getValidationService(); void setValidationService(ValidationService validationService); void setBeforeOkHandler(Handler beforeOkHandler); OkCancelDialog open(); void addContent(Component c); void addContent(Component c, float expandRatio); boolean isOkPressed(); ValidationDisplayState getValidationDisplayState(); boolean isCancelPressed(); String getOkCaption(); void setOkCaption(String okCaption); String getCancelCaption(); void setCancelCaption(String cancelCaption); static Builder builder(String caption); }### Answer:
@Test public void testBuilder_CancelCaption_NoCancelButton() { OkCancelDialog dialog = OkCancelDialog.builder("") .buttonOption(ButtonOption.OK_ONLY) .cancelCaption("cancel it") .build(); OkCancelDialog dialog2 = OkCancelDialog.builder("") .cancelCaption("cancel it") .buttonOption(ButtonOption.OK_ONLY) .build(); assertThrows(IllegalStateException.class, dialog::getCancelCaption); assertThrows(IllegalStateException.class, dialog2::getCancelCaption); }
@Test public void testContent() { Label content1 = new Label("1"); Label content2 = new Label("2"); OkCancelDialog dialog = OkCancelDialog.builder("caption") .content(content1, content2) .build(); assertThat(DialogTestUtil.getContents(dialog), contains(content1, content2)); }
@Test public void testButtonOption() { OkCancelDialog dialog = OkCancelDialog.builder("").buttonOption(ButtonOption.OK_ONLY).build(); assertThat(DialogTestUtil.getButtons(dialog), hasSize(1)); } |
### Question:
OkCancelDialog extends Window { @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "yeah, we know...") @Override public void setContent(@CheckForNull Component content) { if (mainArea == null) { super.setContent(content); } else { mainArea.removeAllComponents(); mainArea.addComponent(content); } } protected OkCancelDialog(String caption, Handler okHandler, Handler cancelHandler,
ButtonOption buttonOption, Component... contentComponents); @Deprecated OkCancelDialog(String caption); @Deprecated OkCancelDialog(String caption, Handler okHandler); @Deprecated OkCancelDialog(String caption, Handler okHandler, ButtonOption buttonOption); @Deprecated OkCancelDialog(String caption, Component content, Handler okHandler, ButtonOption buttonOption); @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "yeah, we know...") @Override void setContent(@CheckForNull Component content); void setSize(String width, String height); MessageList validate(); ValidationService getValidationService(); void setValidationService(ValidationService validationService); void setBeforeOkHandler(Handler beforeOkHandler); OkCancelDialog open(); void addContent(Component c); void addContent(Component c, float expandRatio); boolean isOkPressed(); ValidationDisplayState getValidationDisplayState(); boolean isCancelPressed(); String getOkCaption(); void setOkCaption(String okCaption); String getCancelCaption(); void setCancelCaption(String cancelCaption); static Builder builder(String caption); }### Answer:
@Test public void testSetContent() { OkCancelDialog dialog = OkCancelDialog.builder("").build(); assertThat(DialogTestUtil.getContents(dialog).size(), is(0)); dialog.setContent(new Label()); assertThat(DialogTestUtil.getContents(dialog), hasSize(1)); assertThat(dialog, is(showingEnabledOkButton())); } |
### Question:
OkCancelDialog extends Window { protected void ok() { okHandler.apply(); } protected OkCancelDialog(String caption, Handler okHandler, Handler cancelHandler,
ButtonOption buttonOption, Component... contentComponents); @Deprecated OkCancelDialog(String caption); @Deprecated OkCancelDialog(String caption, Handler okHandler); @Deprecated OkCancelDialog(String caption, Handler okHandler, ButtonOption buttonOption); @Deprecated OkCancelDialog(String caption, Component content, Handler okHandler, ButtonOption buttonOption); @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "yeah, we know...") @Override void setContent(@CheckForNull Component content); void setSize(String width, String height); MessageList validate(); ValidationService getValidationService(); void setValidationService(ValidationService validationService); void setBeforeOkHandler(Handler beforeOkHandler); OkCancelDialog open(); void addContent(Component c); void addContent(Component c, float expandRatio); boolean isOkPressed(); ValidationDisplayState getValidationDisplayState(); boolean isCancelPressed(); String getOkCaption(); void setOkCaption(String okCaption); String getCancelCaption(); void setCancelCaption(String cancelCaption); static Builder builder(String caption); }### Answer:
@Test public void testOk() { Handler okHandler = mock(Handler.class); Handler cancelHandler = mock(Handler.class); OkCancelDialog dialog = OkCancelDialog.builder("") .okHandler(okHandler) .cancelHandler(cancelHandler) .build(); dialog.open(); assertThat(UI.getCurrent().getWindows(), hasSize(1)); DialogTestUtil.clickOkButton(dialog); verify(okHandler).apply(); verify(cancelHandler, never()).apply(); assertThat(UI.getCurrent().getWindows(), hasSize(0)); } |
### Question:
DateFormats { public static void register(String languageCode, String pattern) { LANGUAGE_PATTERNS.put(languageCode, pattern); } private DateFormats(); static void register(String languageCode, String pattern); static String getPattern(Locale locale); static final String PATTERN_ISO; static final String PATTERN_DE; }### Answer:
@Test public void testRegister() { String customPattern = "yyMMdd"; DateFormats.register("foobar", customPattern); assertThat(DateFormats.getPattern(new Locale("foobar")), is(customPattern)); } |
### Question:
OkCancelDialog extends Window { public void setOkCaption(String okCaption) { okButton.setCaption(requireNonNull(okCaption, "okCaption must not be null")); } protected OkCancelDialog(String caption, Handler okHandler, Handler cancelHandler,
ButtonOption buttonOption, Component... contentComponents); @Deprecated OkCancelDialog(String caption); @Deprecated OkCancelDialog(String caption, Handler okHandler); @Deprecated OkCancelDialog(String caption, Handler okHandler, ButtonOption buttonOption); @Deprecated OkCancelDialog(String caption, Component content, Handler okHandler, ButtonOption buttonOption); @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "yeah, we know...") @Override void setContent(@CheckForNull Component content); void setSize(String width, String height); MessageList validate(); ValidationService getValidationService(); void setValidationService(ValidationService validationService); void setBeforeOkHandler(Handler beforeOkHandler); OkCancelDialog open(); void addContent(Component c); void addContent(Component c, float expandRatio); boolean isOkPressed(); ValidationDisplayState getValidationDisplayState(); boolean isCancelPressed(); String getOkCaption(); void setOkCaption(String okCaption); String getCancelCaption(); void setCancelCaption(String cancelCaption); static Builder builder(String caption); }### Answer:
@Test public void testSetOkCaption() { OkCancelDialog dialog = OkCancelDialog.builder("").build(); dialog.setOkCaption("confirm it"); assertThat(dialog.getOkCaption(), is("confirm it")); assertThat(DialogTestUtil.getButtons(dialog).get(0).getCaption(), is("confirm it")); } |
### Question:
OkCancelDialog extends Window { public void setCancelCaption(String cancelCaption) { if (cancelButton != null) { cancelButton.setCaption(requireNonNull(cancelCaption, "cancelCaption must not be null")); } else { throw new IllegalStateException("Dialog does not have a cancel button"); } } protected OkCancelDialog(String caption, Handler okHandler, Handler cancelHandler,
ButtonOption buttonOption, Component... contentComponents); @Deprecated OkCancelDialog(String caption); @Deprecated OkCancelDialog(String caption, Handler okHandler); @Deprecated OkCancelDialog(String caption, Handler okHandler, ButtonOption buttonOption); @Deprecated OkCancelDialog(String caption, Component content, Handler okHandler, ButtonOption buttonOption); @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "yeah, we know...") @Override void setContent(@CheckForNull Component content); void setSize(String width, String height); MessageList validate(); ValidationService getValidationService(); void setValidationService(ValidationService validationService); void setBeforeOkHandler(Handler beforeOkHandler); OkCancelDialog open(); void addContent(Component c); void addContent(Component c, float expandRatio); boolean isOkPressed(); ValidationDisplayState getValidationDisplayState(); boolean isCancelPressed(); String getOkCaption(); void setOkCaption(String okCaption); String getCancelCaption(); void setCancelCaption(String cancelCaption); static Builder builder(String caption); }### Answer:
@Test public void testSetCancelCaption() { OkCancelDialog dialog = OkCancelDialog.builder("").build(); dialog.setCancelCaption("cancel it"); assertThat(dialog.getCancelCaption(), is("cancel it")); assertThat(DialogTestUtil.getButtons(dialog).get(1).getCaption(), is("cancel it")); } |
### Question:
PmoBasedDialogFactory { public OkCancelDialog newOkDialog(String title, Object... pmos) { return newOkCancelDialog(title, Handler.NOP_HANDLER, Handler.NOP_HANDLER, ButtonOption.OK_ONLY, pmos); } PmoBasedDialogFactory(); PmoBasedDialogFactory(ValidationService validationService); PmoBasedDialogFactory(PropertyBehavior... propertyBehavior); PmoBasedDialogFactory(ValidationService validationService,
PropertyBehaviorProvider propertyBehaviorProvider); @Deprecated OkCancelDialog newOkCancelDialog(String title, Object pmo, Handler okHandler); OkCancelDialog newOkDialog(String title, Object... pmos); OkCancelDialog newOkCancelDialog(String title, Handler okHandler, Object... pmos); OkCancelDialog newOkCancelDialog(String title, Handler okHandler, Handler cancelHandler, Object... pmos); OkCancelDialog openOkDialog(String title, Object... pmos); @Deprecated OkCancelDialog openOkCancelDialog(String title, Object pmo, Handler okHandler); OkCancelDialog openOkCancelDialog(String title, Handler okHandler, Object... pmos); OkCancelDialog openOkCancelDialog(String title, Handler okHandler, Handler cancelHandler, Object... pmos); @Deprecated static OkCancelDialog open(OkCancelDialog dialog); }### Answer:
@Test public void testNewOkDialog() { OkCancelDialog dialog = new PmoBasedDialogFactory().newOkDialog("title", new TestPmo()); List<AbstractField<?>> fields = getAllFields(dialog); assertThat(fields, hasSize(1)); assertThat(fields.get(0), is(instanceOf(TextField.class))); assertThat(dialog.getCaption(), is("title")); }
@Test public void testNewOkDialog_noPmo() { OkCancelDialog dialog = new PmoBasedDialogFactory().newOkDialog("title"); assertThat(getAllFields(dialog), hasSize(0)); }
@Test public void testNewOkDialog_MultiplePmos() { OkCancelDialog dialog = new PmoBasedDialogFactory().newOkDialog("title", new TestPmo(), new TestPmo()); List<AbstractField<?>> fields = getAllFields(dialog); assertThat(fields, hasSize(2)); fields.forEach(f -> assertThat(f, is(instanceOf(TextField.class)))); assertThat(dialog.getCaption(), is("title")); } |
### Question:
LazyInitializingMap { @CheckForNull public V getIfPresent(K key) { return internalMap.get(key); } LazyInitializingMap(Function<K, V> initializer); V get(K key); @CheckForNull V getIfPresent(K key); void clear(); @CheckForNull V remove(K key); }### Answer:
@Test public void testGetIfPresent() { LazyInitializingMap<String, Object> lazyInitializingMap = new LazyInitializingMap<>(initializer); Object value = lazyInitializingMap.getIfPresent("string"); assertNull(value); } |
### Question:
ComponentFactory { public static DateField newDateField() { MultiformatDateField field = new MultiformatDateField(); field.setRangeStart(LocalDate.ofYearDay(1, 1)); field.setRangeEnd(LocalDate.ofYearDay(9999, 365)); return field; } private ComponentFactory(); @Deprecated static Label addHorizontalSpacer(AbstractLayout layout); @Deprecated static Label addHorizontalFixedSizeSpacer(AbstractOrderedLayout layout, int px); @Deprecated static final Label newLabelWidth100(AbstractOrderedLayout parent, String caption); @Deprecated static final Label sizedLabel(Layout parent, String caption, ContentMode mode); @Deprecated static final Label sizedLabel(AbstractOrderedLayout parent, String caption); @Deprecated static final Label newLabelWidthUndefined(AbstractOrderedLayout parent, String caption); @Deprecated static Label labelIcon(AbstractOrderedLayout parent, FontIcon icon); @Deprecated static final Label newEmptyLabel(AbstractOrderedLayout layout); static Label newHorizontalLine(); static Label newLabelIcon(FontIcon icon); static Label newLabelFullWidth(String caption, ContentMode contentMode); static Label newLabelFullWidth(String caption); static Label newLabelUndefinedWidth(String caption, ContentMode contentMode); static Label newLabelUndefinedWidth(String caption); static Link newLinkFullWidth(String caption); @Deprecated static TextField newTextfield(); static TextField newTextField(); static TextField newTextField(int maxLength, String width); static TextArea newTextArea(); static TextArea newTextArea(int maxLength, String width, int rows); @Deprecated static TextField newReadOnlyTextFieldFixedWidth(String value); @Deprecated static TextField newReadOnlyTextField(String value, int columns); @Deprecated static TextField newReadOnlyTextField100PctWidth(String value); @Deprecated static TextField newReadOnlyTextField(String value); static ComboBox<T> newComboBox(); static CheckBox newCheckBox(); static Button newButton(); static DateField newDateField(); @Deprecated static TextField newIntegerField(@SuppressWarnings("unused") Locale locale); @Deprecated static TextField newDoubleField(@SuppressWarnings("unused") Locale locale); @Deprecated static Button newButton(ButtonPmo buttonPmo); static Button newButton(Resource icon, Collection<String> styleNames); static TwinColSelect<T> newTwinColSelect(); static VerticalLayout newPlainVerticalLayout(); static final String NO_BREAK_SPACE; }### Answer:
@Test public void testNewDateField_BelowRange() { DateField dateField = ComponentFactory.newDateField(); dateField.setDateOutOfRangeMessage(MESSAGE); assertThrows(IllegalArgumentException.class, () -> dateField.setValue(LocalDate.of(-1, 1, 1))); }
@Test public void testNewDateField_InRangeLowerBound() { DateField dateField = ComponentFactory.newDateField(); dateField.setDateOutOfRangeMessage(MESSAGE); dateField.setValue(LocalDate.of(1, 1, 1)); assertThat(dateField.getErrorMessage(), is(nullValue())); }
@Test public void testNewDateField_InRangeUpperBound() { DateField dateField = ComponentFactory.newDateField(); dateField.setDateOutOfRangeMessage(MESSAGE); dateField.setValue(LocalDate.of(9999, 12, 31)); assertThat(dateField.getErrorMessage(), is(nullValue())); }
@Test public void testNewDateField_AboveRange() { DateField dateField = ComponentFactory.newDateField(); dateField.setDateOutOfRangeMessage(MESSAGE); assertThrows(IllegalArgumentException.class, () -> dateField.setValue(LocalDate.of(10000, 1, 1))); } |
### Question:
AbstractSection extends VerticalLayout { public void addHeaderButton(Button button) { button.addStyleName(LinkkiTheme.BUTTON_TEXT); headerComponents.add(button); header.addComponent(button, 1); updateHeader(); } AbstractSection(@CheckForNull String caption); AbstractSection(@CheckForNull String caption, boolean closeable); @Deprecated AbstractSection(@CheckForNull String caption, boolean closeable, Optional<Button> editButton); @Override void setCaption(@CheckForNull String caption); void addHeaderButton(Button button); void addHeaderComponent(Component component); boolean isOpen(); boolean isClosed(); void open(); void close(); }### Answer:
@Test public void testHeader_AddHeaderButton() { TestSection section = new TestSection("", false); HorizontalLayout header = section.getHeader(); Label captionLabel = (Label)header.getComponent(0); assertThat(header.isVisible(), is(false)); assertThat(captionLabel.isVisible(), is(false)); Button button = ComponentFactory.newButton(); section.addHeaderButton(button); assertThat(header.isVisible(), is(true)); assertThat(captionLabel.isVisible(), is(false)); }
@Test public void testAddHeaderButton() { TestSection section = new TestSection("CAP", true); HorizontalLayout header = section.getHeader(); assertThat(header.getComponentCount(), is(3)); assertThat(header.isVisible(), is(true)); Button button1 = new Button(); section.addHeaderButton(button1); assertThat(header.getComponentCount(), is(4)); assertThat(header.getComponent(1), is(button1)); Button button2 = new Button(); section.addHeaderButton(button2); assertThat(header.getComponentCount(), is(5)); assertThat(header.getComponent(1), is(button2)); assertThat(header.getComponent(2), is(button1)); section.setCaption("UPDATE"); assertThat(header.getComponentCount(), is(5)); assertThat(header.getComponent(1), is(button2)); assertThat(header.getComponent(2), is(button1)); }
@Test public void testHeaderButton_Style() { TestSection section = new TestSection("CAP", true); Button button1 = new Button(); section.addHeaderButton(button1); assertThat(button1.getStyleName(), containsString(LinkkiTheme.BUTTON_TEXT)); } |
### Question:
AbstractSection extends VerticalLayout { @Override public void setCaption(@CheckForNull String caption) { captionLabel.setValue(caption); captionLabel.setVisible(!StringUtils.isEmpty(caption)); updateHeader(); } AbstractSection(@CheckForNull String caption); AbstractSection(@CheckForNull String caption, boolean closeable); @Deprecated AbstractSection(@CheckForNull String caption, boolean closeable, Optional<Button> editButton); @Override void setCaption(@CheckForNull String caption); void addHeaderButton(Button button); void addHeaderComponent(Component component); boolean isOpen(); boolean isClosed(); void open(); void close(); }### Answer:
@Test public void testSetCaption() { TestSection section = new TestSection("CAP", false); HorizontalLayout header = section.getHeader(); Label captionLabel = (Label)header.getComponent(0); assertThat(header.isVisible(), is(true)); assertThat(captionLabel.isVisible(), is(true)); assertThat(captionLabel.getValue(), is("CAP")); section.setCaption("TION"); assertThat(header.isVisible(), is(true)); assertThat(captionLabel.isVisible(), is(true)); assertThat(captionLabel.getValue(), is("TION")); }
@Test public void testSetCaption_Null() { TestSection section = new TestSection("CAP", false); HorizontalLayout header = section.getHeader(); Label captionLabel = (Label)header.getComponent(0); assertThat(header.isVisible(), is(true)); assertThat(captionLabel.isVisible(), is(true)); assertThat(captionLabel.getValue(), is("CAP")); section.setCaption(null); assertThat(header.isVisible(), is(false)); assertThat(captionLabel.isVisible(), is(false)); }
@Test public void testSetCaption_Empty() { TestSection section = new TestSection("CAP", false); HorizontalLayout header = section.getHeader(); Label captionLabel = (Label)header.getComponent(0); assertThat(header.isVisible(), is(true)); assertThat(captionLabel.isVisible(), is(true)); assertThat(captionLabel.getValue(), is("CAP")); section.setCaption(""); assertThat(header.isVisible(), is(false)); assertThat(captionLabel.isVisible(), is(false)); } |
### Question:
LazyInitializingMap { public V get(K key) { @CheckForNull V value = internalMap.computeIfAbsent(key, initializer); if (value == null) { throw new NullPointerException("Initializer must not create a null value"); } return value; } LazyInitializingMap(Function<K, V> initializer); V get(K key); @CheckForNull V getIfPresent(K key); void clear(); @CheckForNull V remove(K key); }### Answer:
@Test public void testGet_null() { LazyInitializingMap<String, Object> lazyInitializingMap = new LazyInitializingMap<>(initializer); Assertions.assertThrows(NullPointerException.class, () -> { lazyInitializingMap.get(null); }); }
@Test public void testGet_initializerFunctionReturnsNull() { LazyInitializingMap<String, Object> lazyInitializingMap = new LazyInitializingMap<>( (String key) -> null); Assertions.assertThrows(NullPointerException.class, () -> { lazyInitializingMap.get("string"); }); }
@Test public void testGet() { LazyInitializingMap<String, Object> lazyInitializingMap = new LazyInitializingMap<>(initializer); assertNull(lazyInitializingMap.getIfPresent("string")); lazyInitializingMap.get("string"); assertNotNull(lazyInitializingMap.getIfPresent("string")); }
@Test public void testGet2() { LazyInitializingMap<String, Object> lazyInitializingMap = new LazyInitializingMap<>(initializer); Object value = lazyInitializingMap.get("string"); assertEquals("stringx", value); Object value2 = lazyInitializingMap.get("string"); assertSame(value, value2); } |
### Question:
TabSheetArea extends TabSheet implements Area { @Override public void reloadBindings() { Component selectedTab = getSelectedTab(); if (selectedTab != null && selectedTab instanceof Page) { ((Page)selectedTab).reloadBindings(); } } TabSheetArea(); TabSheetArea(boolean preserveHeader); @PostConstruct final void init(); @Deprecated TabSheet getTabSheet(); @Override void reloadBindings(); }### Answer:
@Test public void testAddTab_RefreshesFirstTabPage() { TabSheetArea tabSheetArea = new TestArea(); Page tabPage1 = mock(Page.class); Page tabPage2 = mock(Page.class); verify(tabPage1, times(0)).reloadBindings(); verify(tabPage2, times(0)).reloadBindings(); tabSheetArea.addTab(tabPage1, "1"); tabSheetArea.addTab(tabPage2, "2"); verify(tabPage1, times(1)).reloadBindings(); verify(tabPage2, times(0)).reloadBindings(); }
@Test public void testTabSelectionRefreshesPage() { TabSheetArea tabSheetArea = new TestArea(); Page tabPage1 = mock(Page.class); Page tabPage2 = mock(Page.class); tabSheetArea.addTab(tabPage1, "1"); tabSheetArea.addTab(tabPage2, "2"); verify(tabPage2, times(0)).reloadBindings(); tabSheetArea.setSelectedTab(1); verify(tabPage2, times(1)).reloadBindings(); } |
### Question:
TabSheetArea extends TabSheet implements Area { protected List<Page> getTabs() { return StreamUtil.stream(this) .filter(c -> c instanceof Page) .map(c -> (Page)c) .collect(Collectors.toList()); } TabSheetArea(); TabSheetArea(boolean preserveHeader); @PostConstruct final void init(); @Deprecated TabSheet getTabSheet(); @Override void reloadBindings(); }### Answer:
@Test public void testGetTabs() { Page tabPage1 = mock(Page.class); Page tabPage2 = mock(Page.class); TabSheetArea tabSheetArea = new TestArea(); assertThat(tabSheetArea.getTabs(), is(empty())); tabSheetArea.addTab(tabPage1, "1"); tabSheetArea.addTab(tabPage2, "2"); assertThat(tabSheetArea.getTabs(), contains(tabPage1, tabPage2)); } |
### Question:
LinkkiConverterRegistry implements Serializable { @SuppressWarnings("unchecked") public <P, M> Converter<P, M> findConverter(Type presentationType, Type modelType) { Class<?> rawPresentationType = getRawType(presentationType); Class<?> rawModelType = getRawType(modelType); if (isIdentityNecessary(rawPresentationType, rawModelType)) { return (Converter<P, M>)Converter.identity(); } else { return converters.computeIfAbsent(rawPresentationType, t -> Sequence.empty()) .stream() .map(Converter.class::cast) .filter(c -> TypeUtils.equals(getPresentationType(c), rawPresentationType) && TypeUtils.equals(rawModelType, getModelType(c))) .findFirst() .orElseThrow(() -> new IllegalArgumentException( "Cannot convert presentation type " + rawPresentationType + " to model type " + rawModelType)); } } @SafeVarargs LinkkiConverterRegistry(Converter<?, ?>... customConverters); LinkkiConverterRegistry(Collection<Converter<?, ?>> customConverters); LinkkiConverterRegistry(Sequence<Converter<?, ?>> customConverters); @SuppressWarnings("unchecked") Converter<P, M> findConverter(Type presentationType, Type modelType); LinkkiConverterRegistry with(Converter<?, ?> converter); static LinkkiConverterRegistry getCurrent(); static final LinkkiConverterRegistry DEFAULT; }### Answer:
@Test public void testFindConverter_Default() { LinkkiConverterRegistry linkkiConverterRegistry = new LinkkiConverterRegistry(); assertThat(linkkiConverterRegistry.findConverter(String.class, Date.class), is(instanceOf(StringToDateConverter.class))); }
@Test public void testFindConverter_NotFound() { Assertions.assertThrows(IllegalArgumentException.class, () -> { new LinkkiConverterRegistry().findConverter(String.class, java.time.LocalDate.class); }); }
@Test public void testFindConverter_overrideDefault() { LinkkiConverterRegistry linkkiConverterRegistry = new LinkkiConverterRegistry(new MyStringToDateConverter()); assertThat(linkkiConverterRegistry.findConverter(String.class, Date.class), is(instanceOf(MyStringToDateConverter.class))); } |
### Question:
FormattedDoubleToStringConverter extends FormattedNumberToStringConverter<Double> { @Override protected Double convertToModel(Number value) { return value.doubleValue(); } FormattedDoubleToStringConverter(String format); }### Answer:
@Test public void testConvertToModel() { FormattedDoubleToStringConverter converter = new FormattedDoubleToStringConverter("0.00"); ValueContext context = new ValueContext(Locale.GERMAN); assertThat(converter.convertToModel("1,23", context).getOrThrow(s -> new AssertionError(s)), is(1.23)); }
@Test public void testConvertToModel_Null() { FormattedDoubleToStringConverter converter = new FormattedDoubleToStringConverter("0.00"); ValueContext context = new ValueContext(Locale.GERMAN); assertThat(converter.convertToModel("", context).getOrThrow(s -> new AssertionError(s)), is(nullValue())); } |
### Question:
TwoDigitYearLocalDateConverter implements Converter<LocalDate, LocalDate> { @CheckForNull @Override public Result<LocalDate> convertToModel(@CheckForNull LocalDate value, ValueContext context) { if (value == null) { return Result.ok(null); } else { return Result.ok(TwoDigitYearUtil.convert(value)); } } @CheckForNull @Override Result<LocalDate> convertToModel(@CheckForNull LocalDate value, ValueContext context); @Override LocalDate convertToPresentation(LocalDate value, ValueContext context); }### Answer:
@Test public void testConvertToModel_FourDigitYear_NoConversion() { assertThat((converter.convertToModel(LocalDate.of(2039, 12, 31), context)) .getOrThrow(s -> new AssertionError(s)), is(LocalDate.of(2039, 12, 31))); }
@Test public void testConvertToModel_NullValue() { assertNull((converter.convertToModel(null, context)) .getOrThrow(s -> new AssertionError(s))); }
@Test public void testConvertToModel_MaxTwoDigitYear() { LocalDate date = LocalDate.of(39, 12, 31); assertThat((converter.convertToModel(date, context)) .getOrThrow(s -> new AssertionError(s)), is(TwoDigitYearUtil.convert(date))); } |
### Question:
TwoDigitYearLocalDateConverter implements Converter<LocalDate, LocalDate> { @Override public LocalDate convertToPresentation(LocalDate value, ValueContext context) { return value; } @CheckForNull @Override Result<LocalDate> convertToModel(@CheckForNull LocalDate value, ValueContext context); @Override LocalDate convertToPresentation(LocalDate value, ValueContext context); }### Answer:
@Test public void testConvertToPresentation_FourDigitYear_NoConversion() { assertThat((converter.convertToPresentation(LocalDate.of(2011, 9, 5), context)), is(LocalDate.of(2011, 9, 5))); }
@Test public void testConvertToPresentation_NullValue() { assertNull(converter.convertToPresentation(null, context)); }
@Test public void testConvertToPresentation_ThreeDigitYear_NoConversion() { assertThat((converter.convertToPresentation(LocalDate.of(312, 5, 1), context)), is(LocalDate.of(312, 5, 1))); }
@Test public void testConvertToPresentation_TwoDigitYear_NoConversion() { assertThat((converter.convertToPresentation(LocalDate.of(10, 3, 21), context)), is(LocalDate.of(10, 3, 21))); } |
### Question:
FormattedIntegerToStringConverter extends FormattedNumberToStringConverter<Integer> { @Override protected Integer convertToModel(Number value) { return value.intValue(); } FormattedIntegerToStringConverter(String format); }### Answer:
@Test public void testConvertToModel() { FormattedIntegerToStringConverter converter = new FormattedIntegerToStringConverter("#,##0"); ValueContext context = new ValueContext(Locale.GERMAN); assertThat(converter.convertToModel("1.234", context).getOrThrow(s -> new AssertionError(s)), is(1234)); }
@Test public void testConvertToModel_Null() { FormattedIntegerToStringConverter converter = new FormattedIntegerToStringConverter("#,##0"); ValueContext context = new ValueContext(Locale.GERMAN); assertThat(converter.convertToModel("", context).getOrThrow(s -> new AssertionError(s)), is(nullValue())); } |
### Question:
HasItemsAvailableValuesAspectDefinition extends AvailableValuesAspectDefinition<HasItems<?>> { @SuppressWarnings("unchecked") private static void setDataProvider(HasItems<?> component, ListDataProvider<Object> listDataProvider) { if (component instanceof HasDataProvider) { ((HasDataProvider<Object>)component).setDataProvider(listDataProvider); } else if (component instanceof ComboBox) { ((ComboBox<Object>)component).setDataProvider(listDataProvider); } else if (component instanceof HasFilterableDataProvider) { ((HasFilterableDataProvider<Object, SerializablePredicate<Object>>)component) .setDataProvider(listDataProvider); } } HasItemsAvailableValuesAspectDefinition(AvailableValuesType availableValuesType); }### Answer:
@Test public void testSetDataProvider_HasDataProvider() { HasItemsAvailableValuesAspectDefinition hasItemsAvailableValuesAspectDefinition = new HasItemsAvailableValuesAspectDefinition( AvailableValuesType.DYNAMIC); @SuppressWarnings("unchecked") ListDataProvider<Object> dataProvider = mock(ListDataProvider.class); @SuppressWarnings("unchecked") HasDataProvider<Object> component = mock(HasDataProvider.class, withSettings().extraInterfaces(Component.class)); hasItemsAvailableValuesAspectDefinition.setDataProvider(new LabelComponentWrapper(component), dataProvider); verify(component).setDataProvider(dataProvider); }
@Test public void testSetDataProvider_HasFilterableDataProvider() { HasItemsAvailableValuesAspectDefinition hasItemsAvailableValuesAspectDefinition = new HasItemsAvailableValuesAspectDefinition( AvailableValuesType.DYNAMIC); @SuppressWarnings("unchecked") ListDataProvider<Object> dataProvider = mock(ListDataProvider.class); @SuppressWarnings("unchecked") HasFilterableDataProvider<Object, SerializablePredicate<Object>> component = mock(HasFilterableDataProvider.class, withSettings() .extraInterfaces(Component.class)); hasItemsAvailableValuesAspectDefinition.setDataProvider(new LabelComponentWrapper(component), dataProvider); verify(component).setDataProvider(dataProvider); }
@Test public void testSetDataProvider_Other() { HasItemsAvailableValuesAspectDefinition hasItemsAvailableValuesAspectDefinition = new HasItemsAvailableValuesAspectDefinition( AvailableValuesType.DYNAMIC); @SuppressWarnings("unchecked") ListDataProvider<Object> dataProvider = mock(ListDataProvider.class); Component component = mock(HasItems.class, withSettings().extraInterfaces(Component.class)); hasItemsAvailableValuesAspectDefinition.setDataProvider(new LabelComponentWrapper(component), dataProvider); verifyNoMoreInteractions(component); } |
### Question:
HasItemsAvailableValuesAspectDefinition extends AvailableValuesAspectDefinition<HasItems<?>> { @SuppressWarnings("unchecked") @Override protected void handleNullItems(ComponentWrapper componentWrapper, List<?> items) { Object component = componentWrapper.getComponent(); if (component instanceof ComboBox<?>) { boolean hasNullItem = items.removeIf(i -> i == null); ((ComboBox<Object>)component).setEmptySelectionAllowed(hasNullItem); } else if (component instanceof NativeSelect<?>) { boolean hasNullItem = items.removeIf(i -> i == null); ((NativeSelect<Object>)component).setEmptySelectionAllowed(hasNullItem); } } HasItemsAvailableValuesAspectDefinition(AvailableValuesType availableValuesType); }### Answer:
@Test public void testHandleNullItems_ComboBox() { HasItemsAvailableValuesAspectDefinition hasItemsAvailableValuesAspectDefinition = new HasItemsAvailableValuesAspectDefinition( AvailableValuesType.DYNAMIC); ComboBox<TestEnum> comboBox = new ComboBox<>(); hasItemsAvailableValuesAspectDefinition.handleNullItems(new LabelComponentWrapper(comboBox), new LinkedList<>(Arrays.asList(TestEnum.ONE, null))); assertThat(comboBox.isEmptySelectionAllowed()); hasItemsAvailableValuesAspectDefinition.handleNullItems(new LabelComponentWrapper(comboBox), new LinkedList<>(Arrays.asList(TestEnum.TWO))); assertThat(comboBox.isEmptySelectionAllowed(), is(false)); }
@Test public void testHandleNullItems_NativeSelect() { HasItemsAvailableValuesAspectDefinition hasItemsAvailableValuesAspectDefinition = new HasItemsAvailableValuesAspectDefinition( AvailableValuesType.DYNAMIC); NativeSelect<TestEnum> nativeSelect = new NativeSelect<>(); hasItemsAvailableValuesAspectDefinition.handleNullItems(new LabelComponentWrapper(nativeSelect), new LinkedList<>(Arrays.asList(TestEnum.ONE, null))); assertThat(nativeSelect.isEmptySelectionAllowed()); hasItemsAvailableValuesAspectDefinition.handleNullItems(new LabelComponentWrapper(nativeSelect), new LinkedList<>(Arrays.asList(TestEnum.TWO))); assertThat(nativeSelect.isEmptySelectionAllowed(), is(false)); }
@Test public void testHandleNullItems_Other() { HasItemsAvailableValuesAspectDefinition hasItemsAvailableValuesAspectDefinition = new HasItemsAvailableValuesAspectDefinition( AvailableValuesType.DYNAMIC); Component component = mock(HasItems.class, withSettings().extraInterfaces(Component.class)); hasItemsAvailableValuesAspectDefinition.handleNullItems(new LabelComponentWrapper(component), new LinkedList<>(Arrays.asList(TestEnum.ONE, null))); verifyNoMoreInteractions(component); hasItemsAvailableValuesAspectDefinition.handleNullItems(new LabelComponentWrapper(component), new LinkedList<>(Arrays.asList(TestEnum.TWO))); verifyNoMoreInteractions(component); } |
### Question:
CaptionAspectDefinition extends ModelToUiAspectDefinition<String> { @Override public Aspect<String> createAspect() { switch (captionType) { case AUTO: return StringUtils.isEmpty(staticCaption) ? Aspect.of(NAME) : Aspect.of(NAME, staticCaption); case DYNAMIC: return Aspect.of(NAME); case STATIC: return Aspect.of(NAME, staticCaption); case NONE: return Aspect.of(NAME, null); default: throw new IllegalArgumentException("CaptionType " + captionType + " is not supported."); } } CaptionAspectDefinition(CaptionType captionType, String staticCaption); @Override Aspect<String> createAspect(); @Override Consumer<String> createComponentValueSetter(ComponentWrapper componentWrapper); @Override boolean supports(WrapperType type); static final String NAME; }### Answer:
@Test public void testCreateAspect_Static() { CaptionAspectDefinition captionAspectDefinition = new CaptionAspectDefinition(CaptionType.STATIC, "foo"); Aspect<String> aspect = captionAspectDefinition.createAspect(); assertThat(aspect.getName(), is(CaptionAspectDefinition.NAME)); assertThat(aspect.getValue(), is("foo")); }
@Test public void testCreateAspect_Auto_WithValue() { CaptionAspectDefinition captionAspectDefinition = new CaptionAspectDefinition(CaptionType.AUTO, "foo"); Aspect<String> aspect = captionAspectDefinition.createAspect(); assertThat(aspect.getName(), is(CaptionAspectDefinition.NAME)); assertThat(aspect.getValue(), is("foo")); }
@Test public void testCreateAspect_Auto_WithoutValue() { CaptionAspectDefinition captionAspectDefinition = new CaptionAspectDefinition(CaptionType.AUTO, ""); Aspect<String> aspect = captionAspectDefinition.createAspect(); assertThat(aspect.getName(), is(CaptionAspectDefinition.NAME)); assertThat(aspect.isValuePresent(), is(false)); }
@Test public void testCreateAspect_Dynamic() { CaptionAspectDefinition captionAspectDefinition = new CaptionAspectDefinition(CaptionType.DYNAMIC, "foo"); Aspect<String> aspect = captionAspectDefinition.createAspect(); assertThat(aspect.getName(), is(CaptionAspectDefinition.NAME)); assertThat(aspect.isValuePresent(), is(false)); }
@Test public void testCreateAspect_None() { CaptionAspectDefinition captionAspectDefinition = new CaptionAspectDefinition(CaptionType.NONE, "foo"); Aspect<String> aspect = captionAspectDefinition.createAspect(); assertThat(aspect.getName(), is(CaptionAspectDefinition.NAME)); assertThat(aspect.getValue(), is(nullValue())); } |
### Question:
CaptionAspectDefinition extends ModelToUiAspectDefinition<String> { @Override public Consumer<String> createComponentValueSetter(ComponentWrapper componentWrapper) { return caption -> ((Component)componentWrapper.getComponent()).setCaption(caption); } CaptionAspectDefinition(CaptionType captionType, String staticCaption); @Override Aspect<String> createAspect(); @Override Consumer<String> createComponentValueSetter(ComponentWrapper componentWrapper); @Override boolean supports(WrapperType type); static final String NAME; }### Answer:
@Test public void testCreateComponentValueSetter() { CaptionAspectDefinition captionAspectDefinition = new CaptionAspectDefinition(CaptionType.DYNAMIC, "foo"); Component component = new Label(); ComponentWrapper componentWrapper = new LabelComponentWrapper(component); Consumer<String> componentValueSetter = captionAspectDefinition.createComponentValueSetter(componentWrapper); componentValueSetter.accept("bar"); assertThat(component.getCaption(), is("bar")); } |
### Question:
CaptionAspectDefinition extends ModelToUiAspectDefinition<String> { @Override public boolean supports(WrapperType type) { return super.supports(type) && !ColumnBasedComponentWrapper.COLUMN_BASED_TYPE.isAssignableFrom(type); } CaptionAspectDefinition(CaptionType captionType, String staticCaption); @Override Aspect<String> createAspect(); @Override Consumer<String> createComponentValueSetter(ComponentWrapper componentWrapper); @Override boolean supports(WrapperType type); static final String NAME; }### Answer:
@Test public void testCreateComponentValueSetter_NOPonTable() { CaptionAspectDefinition captionAspectDefinition = new CaptionAspectDefinition(CaptionType.DYNAMIC, "foo"); @SuppressWarnings("deprecation") com.vaadin.v7.ui.Table table = new com.vaadin.v7.ui.Table(); ComponentWrapper componentWrapper = new TableComponentWrapper<String>("4711", table); boolean supported = captionAspectDefinition.supports(componentWrapper.getType()); assertThat(supported, is(false)); } |
### Question:
LabelValueAspectDefinition extends ModelToUiAspectDefinition<Object> { @Override public Consumer<Object> createComponentValueSetter(ComponentWrapper componentWrapper) { return v -> ((Label)componentWrapper.getComponent()) .setValue(LabelValueAspectDefinition.toString(v)); } @Override Aspect<Object> createAspect(); @Override Consumer<Object> createComponentValueSetter(ComponentWrapper componentWrapper); static final String NAME; }### Answer:
@Test public void testCreateComponentValueSetter_SetsString() { Label label = new Label(); Consumer<Object> valueSetter = new LabelValueAspectDefinition() .createComponentValueSetter(new LabelComponentWrapper(label)); valueSetter.accept("foo"); assertThat(label.getValue(), is("foo")); }
@Test public void testCreateComponentValueSetter_UsesToString() { Label label = new Label(); Consumer<Object> valueSetter = new LabelValueAspectDefinition() .createComponentValueSetter(new LabelComponentWrapper(label)); valueSetter.accept(new Object() { @Override public String toString() { return "bar"; } }); assertThat(label.getValue(), is("bar")); }
@Test public void testCreateComponentValueSetter_UsesStandardConverter() { Label label = new Label(); Consumer<Object> valueSetter = new LabelValueAspectDefinition() .createComponentValueSetter(new LabelComponentWrapper(label)); valueSetter.accept(Integer.valueOf(123456)); assertThat(label.getValue(), is("123.456")); }
@Test public void testCreateComponentValueSetter_UsesStandardConverter_DependingOnUiLocale() { Label label = new Label(); Consumer<Object> valueSetter = new LabelValueAspectDefinition() .createComponentValueSetter(new LabelComponentWrapper(label)); UI ui = MockUi.mockUi(); when(ui.getLocale()).thenReturn(Locale.US); valueSetter.accept(Integer.valueOf(123456)); assertThat(label.getValue(), is("123,456")); }
@Test public void testCreateComponentValueSetter_UsesCustomConverter() { Label label = new Label(); Consumer<Object> valueSetter = new LabelValueAspectDefinition() .createComponentValueSetter(new LabelComponentWrapper(label)); LinkkiConverterRegistry converterRegistry = LinkkiConverterRegistry.DEFAULT .with(new Converter<String, FooBar>() { private static final long serialVersionUID = 1L; @Override public Result<FooBar> convertToModel(String value, ValueContext context) { return Result.ok(FooBar.valueOf(value)); } @Override public String convertToPresentation(FooBar value, ValueContext context) { return value == FooBar.FOO ? "Foo" : "Bar"; } }); VaadinSession vaadinSession = mock(VaadinSession.class); when(vaadinSession.getAttribute(LinkkiConverterRegistry.class)).thenReturn(converterRegistry); VaadinSession.setCurrent(vaadinSession); valueSetter.accept(FooBar.FOO); assertThat(label.getValue(), is("Foo")); } |
### Question:
AvailableValuesAspectDefinition implements LinkkiAspectDefinition { protected AvailableValuesType getAvailableValuesType() { return availableValuesType; } AvailableValuesAspectDefinition(AvailableValuesType availableValuesType,
BiConsumer<C, ListDataProvider<Object>> dataProviderSetter); @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); Aspect<Collection<?>> createAspect(String propertyName, Class<?> valueClass); static final String NAME; }### Answer:
@Test public void testGetAvailableValuesType() { for (AvailableValuesType type : AvailableValuesType.values()) { assertThat(new AvailableValuesAspectDefinition<>(type, NOP).getAvailableValuesType(), is(type)); } } |
### Question:
AvailableValuesAspectDefinition implements LinkkiAspectDefinition { protected <T extends Enum<T>> List<?> getValuesDerivedFromDatatype(String propertyName, Class<?> valueClass) { if (valueClass.isEnum()) { @SuppressWarnings("unchecked") Class<T> enumType = (Class<T>)valueClass; return AvailableValuesProvider.enumToValues(enumType, getAvailableValuesType() == AvailableValuesType.ENUM_VALUES_INCL_NULL); } if (valueClass == Boolean.TYPE) { return AvailableValuesProvider.booleanPrimitiveToValues(); } if (valueClass == Boolean.class) { return AvailableValuesProvider.booleanWrapperToValues(); } else { throw new IllegalStateException( "Cannot retrieve list of available values for " + valueClass.getName() + "#" + propertyName); } } AvailableValuesAspectDefinition(AvailableValuesType availableValuesType,
BiConsumer<C, ListDataProvider<Object>> dataProviderSetter); @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); Aspect<Collection<?>> createAspect(String propertyName, Class<?> valueClass); static final String NAME; }### Answer:
@Test public void testGetValuesDerivedFromDatatype_NonEnumDatatype() { Assertions.assertThrows(IllegalStateException.class, () -> { new AvailableValuesAspectDefinition<>(AvailableValuesType.DYNAMIC, NOP) .getValuesDerivedFromDatatype("foo", String.class); }); }
@Test public void testGetValuesDerivedFromDatatype() { AvailableValuesAspectDefinition<HasItems<?>> availableValuesAspectDefinition = new AvailableValuesAspectDefinition<>( AvailableValuesType.DYNAMIC, NOP); assertThat(availableValuesAspectDefinition.getValuesDerivedFromDatatype("foo", TestEnum.class), contains(TestEnum.ONE, TestEnum.TWO, TestEnum.THREE)); assertThat(availableValuesAspectDefinition.getValuesDerivedFromDatatype("foo", Boolean.class), contains(null, true, false)); assertThat(availableValuesAspectDefinition.getValuesDerivedFromDatatype("foo", boolean.class), contains(true, false)); } |
### Question:
DateFormatRegistry { @Deprecated public String getPattern(Locale locale) { requireNonNull(locale, "locale must not be null"); String registeredPattern = languagePatterns.get(locale.getLanguage()); if (registeredPattern != null) { return registeredPattern; } else { return defaultLocalePattern(locale); } } @Deprecated String getPattern(Locale locale); @Deprecated
static final String PATTERN_ISO; @Deprecated
static final String PATTERN_DE; }### Answer:
@SuppressWarnings("deprecation") @Test public void testGetPattern() { DateFormatRegistry registry = new DateFormatRegistry(); assertThat(registry.getPattern(GERMAN), is(DateFormatRegistry.PATTERN_DE)); assertThat(registry.getPattern(GERMANY), is(DateFormatRegistry.PATTERN_DE)); assertThat(registry.getPattern(AUSTRIA), is(DateFormatRegistry.PATTERN_DE)); assertThat(registry.getPattern(ENGLISH), is(not(nullValue()))); assertThat(registry.getPattern(ENGLISH), is(not(DateFormatRegistry.PATTERN_DE))); assertThat(registry.getPattern(ENGLISH), is(not(DateFormatRegistry.PATTERN_ISO))); assertThat(registry.getPattern(US), is(not(nullValue()))); assertThat(registry.getPattern(US), is(not(DateFormatRegistry.PATTERN_DE))); assertThat(registry.getPattern(US), is(not(DateFormatRegistry.PATTERN_ISO))); } |
### Question:
AvailableValuesAspectDefinition implements LinkkiAspectDefinition { @SuppressWarnings("unchecked") protected void setDataProvider(ComponentWrapper componentWrapper, ListDataProvider<Object> dataProvider) { dataProviderSetter.accept((C)componentWrapper.getComponent(), dataProvider); } AvailableValuesAspectDefinition(AvailableValuesType availableValuesType,
BiConsumer<C, ListDataProvider<Object>> dataProviderSetter); @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); Aspect<Collection<?>> createAspect(String propertyName, Class<?> valueClass); static final String NAME; }### Answer:
@Test public void testSetDataProvider() { @SuppressWarnings("unchecked") BiConsumer<HasItems<?>, ListDataProvider<Object>> dataProviderSetter = mock(BiConsumer.class); AvailableValuesAspectDefinition<HasItems<?>> availableValuesAspectDefinition = new AvailableValuesAspectDefinition<>( AvailableValuesType.DYNAMIC, dataProviderSetter); @SuppressWarnings("unchecked") ListDataProvider<Object> dataProvider = mock(ListDataProvider.class); ComboBox<Object> component = new ComboBox<>(); availableValuesAspectDefinition.setDataProvider(new LabelComponentWrapper(component), dataProvider); verify(dataProviderSetter).accept(component, dataProvider); } |
### Question:
AvailableValuesAspectDefinition implements LinkkiAspectDefinition { protected void handleNullItems(ComponentWrapper componentWrapper, List<?> items) { } AvailableValuesAspectDefinition(AvailableValuesType availableValuesType,
BiConsumer<C, ListDataProvider<Object>> dataProviderSetter); @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); Aspect<Collection<?>> createAspect(String propertyName, Class<?> valueClass); static final String NAME; }### Answer:
@Test public void testHandleNullItems() { AvailableValuesAspectDefinition<HasItems<?>> availableValuesAspectDefinition = new AvailableValuesAspectDefinition<>( AvailableValuesType.DYNAMIC, NOP); @SuppressWarnings("unchecked") List<Object> items = mock(List.class); @SuppressWarnings("unchecked") ComboBox<Object> component = mock(ComboBox.class); availableValuesAspectDefinition.handleNullItems(new LabelComponentWrapper(component), items); verifyNoMoreInteractions(component, items); } |
### Question:
AvailableValuesAspectDefinition implements LinkkiAspectDefinition { public Aspect<Collection<?>> createAspect(String propertyName, Class<?> valueClass) { AvailableValuesType type = getAvailableValuesType(); if (type == AvailableValuesType.DYNAMIC) { return Aspect.of(NAME); } else if (type == AvailableValuesType.NO_VALUES) { return Aspect.of(NAME, new ArrayList<>()); } else { return Aspect.of(NAME, getValuesDerivedFromDatatype(propertyName, valueClass)); } } AvailableValuesAspectDefinition(AvailableValuesType availableValuesType,
BiConsumer<C, ListDataProvider<Object>> dataProviderSetter); @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); Aspect<Collection<?>> createAspect(String propertyName, Class<?> valueClass); static final String NAME; }### Answer:
@Test public void testCreateAspect_Dynamic() { AvailableValuesAspectDefinition<HasItems<?>> availableValuesAspectDefinition = new AvailableValuesAspectDefinition<>( AvailableValuesType.DYNAMIC, NOP); Aspect<Collection<?>> aspect = availableValuesAspectDefinition.createAspect("foo", TestEnum.class); assertThat(aspect.getName(), is(AvailableValuesAspectDefinition.NAME)); assertThat(aspect.isValuePresent(), is(false)); }
@Test public void testCreateAspect_NoValues() { AvailableValuesAspectDefinition<HasItems<?>> availableValuesAspectDefinition = new AvailableValuesAspectDefinition<>( AvailableValuesType.NO_VALUES, NOP); Aspect<Collection<?>> aspect = availableValuesAspectDefinition.createAspect("foo", TestEnum.class); assertThat(aspect.getName(), is(AvailableValuesAspectDefinition.NAME)); assertThat(aspect.isValuePresent(), is(true)); assertThat(aspect.getValue(), is(empty())); }
@Test public void testCreateAspect_EnumValuesExclNull() { AvailableValuesAspectDefinition<HasItems<?>> availableValuesAspectDefinition = new AvailableValuesAspectDefinition<>( AvailableValuesType.ENUM_VALUES_EXCL_NULL, NOP); Aspect<Collection<?>> aspect = availableValuesAspectDefinition.createAspect("foo", TestEnum.class); assertThat(aspect.getName(), is(AvailableValuesAspectDefinition.NAME)); assertThat(aspect.isValuePresent(), is(true)); assertThat(aspect.getValue(), contains(TestEnum.ONE, TestEnum.TWO, TestEnum.THREE)); }
@Test public void testCreateAspect_EnumValuesInclNull() { AvailableValuesAspectDefinition<HasItems<?>> availableValuesAspectDefinition = new AvailableValuesAspectDefinition<>( AvailableValuesType.ENUM_VALUES_INCL_NULL, NOP); Aspect<Collection<?>> aspect = availableValuesAspectDefinition.createAspect("foo", TestEnum.class); assertThat(aspect.getName(), is(AvailableValuesAspectDefinition.NAME)); assertThat(aspect.isValuePresent(), is(true)); assertThat(aspect.getValue(), contains(null, TestEnum.ONE, TestEnum.TWO, TestEnum.THREE)); } |
### Question:
AvailableValuesAspectDefinition implements LinkkiAspectDefinition { @Override public Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper) { Aspect<Collection<?>> aspect = createAspect(propertyDispatcher.getProperty(), propertyDispatcher.getValueClass()); List<Object> items = new ArrayList<>(); ListDataProvider<Object> listDataProvider = new ListDataProvider<>(items); setDataProvider(componentWrapper, listDataProvider); return () -> updateItems(items, propertyDispatcher.pull(aspect), componentWrapper); } AvailableValuesAspectDefinition(AvailableValuesType availableValuesType,
BiConsumer<C, ListDataProvider<Object>> dataProviderSetter); @Override Handler createUiUpdater(PropertyDispatcher propertyDispatcher, ComponentWrapper componentWrapper); Aspect<Collection<?>> createAspect(String propertyName, Class<?> valueClass); static final String NAME; }### Answer:
@SuppressWarnings("unchecked") @Test public void testCreateUiUpdater() { BiConsumer<HasItems<?>, ListDataProvider<Object>> dataProviderSetter = mock(BiConsumer.class); AvailableValuesAspectDefinition<HasItems<?>> availableValuesAspectDefinition = new AvailableValuesAspectDefinition<>( AvailableValuesType.DYNAMIC, dataProviderSetter); PropertyDispatcher propertyDispatcher = mock(PropertyDispatcher.class); when(propertyDispatcher.pull(any(Aspect.class))).thenReturn(Arrays.asList(TestEnum.ONE, TestEnum.THREE)); ComboBox<Object> component = mock(ComboBox.class); Handler uiUpdater = availableValuesAspectDefinition.createUiUpdater(propertyDispatcher, new LabelComponentWrapper(component)); ArgumentCaptor<ListDataProvider<?>> dataProviderCaptor = ArgumentCaptor.forClass(ListDataProvider.class); verify(dataProviderSetter).accept(eq(component), (ListDataProvider<Object>)dataProviderCaptor.capture()); @NonNull ListDataProvider<?> dataProvider = dataProviderCaptor.getValue(); uiUpdater.apply(); assertThat(dataProvider.getItems(), contains(TestEnum.ONE, TestEnum.THREE)); }
@SuppressWarnings("unchecked") @Test public void testRefresh() { BiConsumer<HasItems<?>, ListDataProvider<Object>> dataProviderSetter = mock(BiConsumer.class); AvailableValuesAspectDefinition<HasItems<?>> availableValuesAspectDefinition = new AvailableValuesAspectDefinition<>( AvailableValuesType.DYNAMIC, dataProviderSetter); PropertyDispatcher propertyDispatcher = mock(PropertyDispatcher.class); when(propertyDispatcher.pull(any(Aspect.class))).thenReturn(Arrays.asList(TestEnum.ONE, TestEnum.THREE)); ComboBox<Object> component = mock(ComboBox.class); when(component.getValue()).thenReturn(TestEnum.ONE); Handler uiUpdater = availableValuesAspectDefinition.createUiUpdater(propertyDispatcher, new LabelComponentWrapper(component)); ArgumentCaptor<ListDataProvider<?>> dataProviderCaptor = ArgumentCaptor.forClass(ListDataProvider.class); verify(dataProviderSetter).accept(eq(component), (ListDataProvider<Object>)dataProviderCaptor.capture()); @NonNull ListDataProvider<Object> dataProvider = (ListDataProvider<Object>)dataProviderCaptor.getValue(); Mockito.reset(dataProviderSetter); uiUpdater.apply(); verify(dataProviderSetter).accept(eq(component), (ListDataProvider<Object>)dataProviderCaptor.capture()); ListDataProvider<Object> newDataProvider = (ListDataProvider<Object>)dataProviderCaptor.getValue(); assertThat(newDataProvider, is(not(dataProvider))); } |
### Question:
TableCreator implements ColumnBasedComponentCreator { @SuppressWarnings("deprecation") @Override public ComponentWrapper createComponent(ContainerPmo<?> containerPmo) { com.vaadin.v7.ui.Table table = containerPmo.isHierarchical() ? new com.vaadin.v7.ui.TreeTable() : new com.vaadin.v7.ui.Table(); table.addStyleName(LinkkiTheme.TABLE); table.setHeightUndefined(); table.setWidth("100%"); table.setSortEnabled(false); return new TableComponentWrapper<>(containerPmo.getClass().getSimpleName(), table); } @SuppressWarnings("deprecation") @Override ComponentWrapper createComponent(ContainerPmo<?> containerPmo); @SuppressWarnings("deprecation") @Override void initColumn(ContainerPmo<?> containerPmo,
ComponentWrapper tableWrapper,
BindingContext bindingContext,
PropertyElementDescriptors elementDesc); }### Answer:
@Test public void testCreateComponent_PmoClassIsUsedAsId() { TableCreator creator = new TableCreator(); com.vaadin.v7.ui.Table table = (com.vaadin.v7.ui.Table)creator.createComponent(new TestTablePmo()) .getComponent(); assertThat(table.getId(), is("TestTablePmo")); } |
### Question:
HtmlSanitizer { public static @CheckForNull String sanitize(@CheckForNull String text) { if (StringUtils.isEmpty(text)) { return text; } else { return text.replaceAll("<(?!\\/?" + ALLOWED_TAGS + ">)", "<") .replaceAll("(?<!<\\/?" + ALLOWED_TAGS + ")>", ">"); } } private HtmlSanitizer(); static @CheckForNull String sanitize(@CheckForNull String text); }### Answer:
@Test public void testSanitize() { assertThat(HtmlSanitizer.sanitize(null), is(nullValue())); assertThat(HtmlSanitizer.sanitize("<p>"), is("<p>")); assertThat(HtmlSanitizer.sanitize("</p>"), is("</p>")); assertThat(HtmlSanitizer.sanitize("<div>"), is("<div>")); assertThat(HtmlSanitizer.sanitize("</div>"), is("</div>")); assertThat(HtmlSanitizer.sanitize("<span>"), is("<span>")); assertThat(HtmlSanitizer.sanitize("</span>"), is("</span>")); assertThat(HtmlSanitizer.sanitize("<br>"), is("<br>")); assertThat(HtmlSanitizer.sanitize("</br>"), is("</br>")); assertThat(HtmlSanitizer.sanitize("<b>"), is("<b>")); assertThat(HtmlSanitizer.sanitize("</b>"), is("</b>")); assertThat(HtmlSanitizer.sanitize("<strong>"), is("<strong>")); assertThat(HtmlSanitizer.sanitize("</strong>"), is("</strong>")); assertThat(HtmlSanitizer.sanitize("<i>"), is("<i>")); assertThat(HtmlSanitizer.sanitize("</i>"), is("</i>")); assertThat(HtmlSanitizer.sanitize("<em>"), is("<em>")); assertThat(HtmlSanitizer.sanitize("</em>"), is("</em>")); assertThat(HtmlSanitizer.sanitize("<u>"), is("<u>")); assertThat(HtmlSanitizer.sanitize("</u>"), is("</u>")); assertThat(HtmlSanitizer.sanitize("<script>"), is("<script>")); assertThat(HtmlSanitizer.sanitize("</script>"), is("</script>")); assertThat(HtmlSanitizer.sanitize("<style>"), is("<style>")); assertThat(HtmlSanitizer.sanitize("</style>"), is("</style>")); assertThat(HtmlSanitizer.sanitize("<"), is("<")); assertThat(HtmlSanitizer.sanitize(">"), is(">")); assertThat(HtmlSanitizer.sanitize("div"), is("div")); assertThat(HtmlSanitizer.sanitize("<div"), is("<div")); assertThat(HtmlSanitizer.sanitize("div>"), is("div>")); } |
### Question:
LinkkiInMemoryContainer extends com.vaadin.v7.data.util.AbstractInMemoryContainer<T, Object, com.vaadin.v7.data.Item> implements com.vaadin.v7.data.Container.Hierarchical { public void setItems(Collection<? extends T> items) { requireNonNull(items, "items must not be null"); this.roots = new ArrayList<>(items); getAllItemIds().clear(); getAllItemIds().addAll(items); fireItemSetChange(); } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override com.vaadin.v7.data.Property<T> getContainerProperty(@CheckForNull Object itemId,
@CheckForNull Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testBackupListShouldBeClearedOnRemoveAllItems() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); container.setItems(Collections.singletonList(new TestItem())); assertThat(container.getItemIds(), hasSize(1)); container.setItems(Collections.emptyList()); assertThat(container.getItemIds(), hasSize(0)); }
@Test public void testEqualsOfWrapperShouldOnlyCheckReference() { TestItem testItem = new TestItem(42); LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); container.setItems(Collections.singletonList(testItem)); TestItem equalItem = new TestItem(42); assertThat(testItem, is(equalItem)); assertThat(container.getItemIds().get(0), is(equalItem)); assertThat(container.getItemIds().get(0), is(testItem)); } |
### Question:
LinkkiInMemoryContainer extends com.vaadin.v7.data.util.AbstractInMemoryContainer<T, Object, com.vaadin.v7.data.Item> implements com.vaadin.v7.data.Container.Hierarchical { @Override @SuppressWarnings({ "unchecked" }) public Collection<T> getChildren(Object itemId) { List<T> newChildren = children.computeIfAbsent((T)itemId, this::getChildrenTypesafe); newChildren.forEach(c -> { if (!containsId(c)) { getAllItemIds().add(c); } }); return newChildren; } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override com.vaadin.v7.data.Property<T> getContainerProperty(@CheckForNull Object itemId,
@CheckForNull Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testGetChildren_ofItemNotContained() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); assertThat(container.getChildren(new TestItem(42)), is(empty())); } |
### Question:
LinkkiInMemoryContainer extends com.vaadin.v7.data.util.AbstractInMemoryContainer<T, Object, com.vaadin.v7.data.Item> implements com.vaadin.v7.data.Container.Hierarchical { @CheckForNull @Override public T getParent(Object itemId) { return parents.get(itemId); } @Override Collection<?> getContainerPropertyIds(); void setItems(Collection<? extends T> items); @Deprecated @Override boolean removeAllItems(); @Deprecated void addAllItems(Collection<T> items); @Override com.vaadin.v7.data.Property<T> getContainerProperty(@CheckForNull Object itemId,
@CheckForNull Object propertyId); @Override @CheckForNull Class<?> getType(@CheckForNull Object propertyId); @Override @SuppressWarnings({ "unchecked" }) Collection<T> getChildren(Object itemId); Collection<T> getExistingChildren(T parent); boolean removeExistingChildren(T item); @CheckForNull @Override T getParent(Object itemId); @Override Collection<?> rootItemIds(); @Override boolean areChildrenAllowed(Object itemId); @Override boolean isRoot(Object itemId); @Override boolean hasChildren(Object itemId); @Override boolean setParent(Object itemId, Object newParentId); @Override boolean setChildrenAllowed(Object itemId, boolean areChildrenAllowed); }### Answer:
@Test public void testGetParent_ofItemNotContained() { LinkkiInMemoryContainer<TestItem> container = new LinkkiInMemoryContainer<>(); assertThat(container.getParent(new TestItem(42)), is(nullValue())); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.