method2testcases
stringlengths 118
3.08k
|
---|
### Question:
IntegerDataItem implements DataItem { @Override public Byte getByte() { return value.byteValue(); } IntegerDataItem(); IntegerDataItem(final int value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }### Answer:
@Test(groups = "fast") public void testConvertToByte() throws Exception { Assert.assertEquals(value0.getByte(), Byte.valueOf((byte) 0)); Assert.assertEquals(value1.getByte(), Byte.valueOf((byte) 1)); Assert.assertEquals(value1000000.getByte(), Byte.valueOf((byte) 64)); Assert.assertEquals(valueMinus1000000.getByte(), Byte.valueOf((byte) -64)); }
|
### Question:
ThriftEnvelopeEvent implements Event { @Override public String getOutputDir(final String prefix) { final GranularityPathMapper pathMapper = new GranularityPathMapper(String.format("%s/%s", prefix, thriftEnvelope.getTypeName()), granularity); return pathMapper.getPathForDateTime(getEventDateTime()); } ThriftEnvelopeEvent(); ThriftEnvelopeEvent(final DateTime eventDateTime, final ThriftEnvelope thriftEnvelope); ThriftEnvelopeEvent(final DateTime eventDateTime, final ThriftEnvelope thriftEnvelope, final Granularity granularity); ThriftEnvelopeEvent(final InputStream in, final ThriftEnvelopeDeserializer deserializer); @Override DateTime getEventDateTime(); @Override String getName(); @Override Granularity getGranularity(); @Override String getVersion(); @Override String getOutputDir(final String prefix); @Override Object getData(); @Override byte[] getSerializedEvent(); @Override void readExternal(final ObjectInput in); @Override void writeExternal(final ObjectOutput out); @Override String toString(); }### Answer:
@Test(groups = "fast") public void testGetOutputDir() throws Exception { final ThriftEnvelope thriftEnvelope = new ThriftEnvelope(eventType); thriftEnvelope.getPayload().add(ThriftField.createThriftField("fuuness", (short) 0)); thriftEnvelope.getPayload().add(ThriftField.createThriftField(100L, (short) 1)); final ThriftEnvelopeEvent event = new ThriftEnvelopeEvent(new DateTime("2009-01-01T02:03:04"), thriftEnvelope); Assert.assertEquals(event.getOutputDir("/events/ning"), String.format("/events/ning/%s/2009/01/01/02", eventType)); }
|
### Question:
ThriftEnvelopeEvent implements Event { @Override public String getVersion() { return thriftEnvelope.getVersion(); } ThriftEnvelopeEvent(); ThriftEnvelopeEvent(final DateTime eventDateTime, final ThriftEnvelope thriftEnvelope); ThriftEnvelopeEvent(final DateTime eventDateTime, final ThriftEnvelope thriftEnvelope, final Granularity granularity); ThriftEnvelopeEvent(final InputStream in, final ThriftEnvelopeDeserializer deserializer); @Override DateTime getEventDateTime(); @Override String getName(); @Override Granularity getGranularity(); @Override String getVersion(); @Override String getOutputDir(final String prefix); @Override Object getData(); @Override byte[] getSerializedEvent(); @Override void readExternal(final ObjectInput in); @Override void writeExternal(final ObjectOutput out); @Override String toString(); }### Answer:
@Test(groups = "fast") public void testVersion1() throws Exception { final ThriftEnvelope thriftEnvelope = new ThriftEnvelope(eventType); thriftEnvelope.getPayload().add(ThriftField.createThriftField(100L, (short) 4)); thriftEnvelope.getPayload().add(ThriftField.createThriftField("fuuness", (short) 1)); final ThriftEnvelopeEvent event = new ThriftEnvelopeEvent(new DateTime("2009-01-01T02:03:04"), thriftEnvelope); Assert.assertEquals(event.getVersion(), "1.4"); }
@Test(groups = "fast") public void testVersion2() throws Exception { final ThriftEnvelope thriftEnvelope = new ThriftEnvelope(eventType); thriftEnvelope.getPayload().add(ThriftField.createThriftField("fuuness", (short) 1)); thriftEnvelope.getPayload().add(ThriftField.createThriftField(100L, (short) 4)); final ThriftEnvelopeEvent event = new ThriftEnvelopeEvent(new DateTime("2009-01-01T02:03:04"), thriftEnvelope); Assert.assertEquals(event.getVersion(), "1.4"); }
|
### Question:
ThriftToThriftEnvelopeEvent { public static <T extends Serializable> ThriftEnvelopeEvent extractEvent(final String eventName, final T thriftObject) { return extractEvent(eventName, new DateTime(), thriftObject); } static ThriftEnvelopeEvent extractEvent(final String eventName, final T thriftObject); static ThriftEnvelopeEvent extractEvent(final String eventName, final DateTime eventDateTime, final T thriftObject); static ThriftEnvelopeEvent extractEvent(final String type, final byte[] payload); static ThriftEnvelopeEvent extractEvent(final String type, final DateTime eventDateTime, final byte[] payload); }### Answer:
@Test public void testExtractEvent() throws Exception { final DateTime eventDateTime = new DateTime(); final String coreHostname = "hostname"; final TLoggingEvent event = new TLoggingEvent(); event.setCoreHostname(coreHostname); final String ip = "10.1.2.3"; event.setCoreIp(ip); final String type = "coic"; event.setCoreType(type); event.setEventDate(eventDateTime.getMillis()); final ThriftEnvelopeEvent envelopeEvent = ThriftToThriftEnvelopeEvent.extractEvent("TLoggingEvent", event); final TLoggingEvent finalEvent = ThriftEnvelopeEventToThrift.extractThrift(TLoggingEvent.class, envelopeEvent); Assert.assertEquals(finalEvent.getCoreHostname(), event.getCoreHostname()); Assert.assertEquals(finalEvent.getCoreHostname(), coreHostname); Assert.assertEquals(finalEvent.getCoreIp(), event.getCoreIp()); Assert.assertEquals(finalEvent.getCoreIp(), ip); Assert.assertEquals(finalEvent.getCoreType(), event.getCoreType()); Assert.assertEquals(finalEvent.getCoreType(), type); Assert.assertEquals(finalEvent.getEventDate(), event.getEventDate()); Assert.assertEquals(finalEvent.getEventDate(), eventDateTime.getMillis()); for (final ThriftField field : ((ThriftEnvelope) envelopeEvent.getData()).getPayload()) { Assert.assertTrue(field.getId() > 0); } }
|
### Question:
ThresholdEventWriter implements EventWriter { @Managed(description = "Commit locally spooled events for flushing") @Override public synchronized void forceCommit() throws IOException { log.debug("Performing commit on delegate EventWriter [{}]", delegate.getClass()); delegate.commit(); uncommittedWriteCount = 0; lastCommitNanos = getNow(); } ThresholdEventWriter(final EventWriter delegate, final long maxUncommittedWriteCount, final long maxUncommittedPeriodInSeconds); @Override synchronized void write(final Event event); @Managed(description = "Commit locally spooled events for flushing") @Override synchronized void forceCommit(); @Override synchronized void commit(); @Override synchronized void rollback(); @Override synchronized void flush(); @Override synchronized void close(); @Override String getSpoolPath(); @Managed(description = "Set the max number of writes before a commit is performed") void setMaxWriteCount(final long maxWriteCount); @Managed(description = "The max number of writes before a commit is performed") long getMaxWriteCount(); @Managed(description = "Set the max number of seconds between commits of local disk spools") void setMaxUncommittedPeriodInSeconds(final long maxUncommittedPeriodInSeconds); @Managed(description = "The max number of seconds between commits of local disk spools") long getMaxUncommittedPeriodInSeconds(); }### Answer:
@Test(groups = "fast") public void testForceCommit() throws Exception { writeAndTestCounts(1, 0); writeAndTestCounts(2, 0); eventWriter.forceCommit(); assertTestCounts(0, 2); }
|
### Question:
ThresholdEventWriter implements EventWriter { @Override public synchronized void commit() throws IOException { commitIfNeeded(); } ThresholdEventWriter(final EventWriter delegate, final long maxUncommittedWriteCount, final long maxUncommittedPeriodInSeconds); @Override synchronized void write(final Event event); @Managed(description = "Commit locally spooled events for flushing") @Override synchronized void forceCommit(); @Override synchronized void commit(); @Override synchronized void rollback(); @Override synchronized void flush(); @Override synchronized void close(); @Override String getSpoolPath(); @Managed(description = "Set the max number of writes before a commit is performed") void setMaxWriteCount(final long maxWriteCount); @Managed(description = "The max number of writes before a commit is performed") long getMaxWriteCount(); @Managed(description = "Set the max number of seconds between commits of local disk spools") void setMaxUncommittedPeriodInSeconds(final long maxUncommittedPeriodInSeconds); @Managed(description = "The max number of seconds between commits of local disk spools") long getMaxUncommittedPeriodInSeconds(); }### Answer:
@Test(groups = "fast") public void testCommit() throws Exception { writeAndTestCounts(1, 0); writeAndTestCounts(2, 0); eventWriter.commit(); assertTestCounts(2, 0); now = now.plusSeconds(301); eventWriter.commit(); assertTestCounts(0, 2); }
|
### Question:
ThresholdEventWriter implements EventWriter { @Override public synchronized void write(final Event event) throws IOException { if (!acceptsEvents) { log.warn("Writer not ready, discarding event: {}", event); return; } delegate.write(event); uncommittedWriteCount++; commitIfNeeded(); } ThresholdEventWriter(final EventWriter delegate, final long maxUncommittedWriteCount, final long maxUncommittedPeriodInSeconds); @Override synchronized void write(final Event event); @Managed(description = "Commit locally spooled events for flushing") @Override synchronized void forceCommit(); @Override synchronized void commit(); @Override synchronized void rollback(); @Override synchronized void flush(); @Override synchronized void close(); @Override String getSpoolPath(); @Managed(description = "Set the max number of writes before a commit is performed") void setMaxWriteCount(final long maxWriteCount); @Managed(description = "The max number of writes before a commit is performed") long getMaxWriteCount(); @Managed(description = "Set the max number of seconds between commits of local disk spools") void setMaxUncommittedPeriodInSeconds(final long maxUncommittedPeriodInSeconds); @Managed(description = "The max number of seconds between commits of local disk spools") long getMaxUncommittedPeriodInSeconds(); }### Answer:
@Test(groups = "fast") public void testWriteException() throws Exception { try { delegateWriter.setWriteThrowsException(true); eventWriter.write(event); Assert.fail("expected exception"); } catch (IOException e) { Assert.assertEquals(e.getClass(), IOException.class); } }
@Test(groups = "fast") public void testCommitException() throws Exception { try { delegateWriter.setCommitThrowsException(true); now = now.plusSeconds(301); eventWriter.write(event); Assert.fail("expected exception"); } catch (IOException e) { Assert.assertEquals(e.getClass(), IOException.class); } }
|
### Question:
ThresholdEventWriter implements EventWriter { @Override public synchronized void rollback() throws IOException { delegate.rollback(); } ThresholdEventWriter(final EventWriter delegate, final long maxUncommittedWriteCount, final long maxUncommittedPeriodInSeconds); @Override synchronized void write(final Event event); @Managed(description = "Commit locally spooled events for flushing") @Override synchronized void forceCommit(); @Override synchronized void commit(); @Override synchronized void rollback(); @Override synchronized void flush(); @Override synchronized void close(); @Override String getSpoolPath(); @Managed(description = "Set the max number of writes before a commit is performed") void setMaxWriteCount(final long maxWriteCount); @Managed(description = "The max number of writes before a commit is performed") long getMaxWriteCount(); @Managed(description = "Set the max number of seconds between commits of local disk spools") void setMaxUncommittedPeriodInSeconds(final long maxUncommittedPeriodInSeconds); @Managed(description = "The max number of seconds between commits of local disk spools") long getMaxUncommittedPeriodInSeconds(); }### Answer:
@Test(groups = "fast") public void testRollbackException() throws Exception { try { delegateWriter.setRollbackThrowsException(true); eventWriter.rollback(); Assert.fail("expected exception"); } catch (IOException e) { Assert.assertEquals(e.getClass(), IOException.class); } }
|
### Question:
IntegerDataItem implements DataItem { @Override public Short getShort() { return value.shortValue(); } IntegerDataItem(); IntegerDataItem(final int value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }### Answer:
@Test(groups = "fast") public void testConvertToShort() throws Exception { Assert.assertEquals(value0.getShort(), Short.valueOf((short) 0)); Assert.assertEquals(value1.getShort(), Short.valueOf((short) 1)); Assert.assertEquals(value1000000.getShort(), Short.valueOf((short) 16960)); Assert.assertEquals(valueMinus1000000.getShort(), Short.valueOf((short) -16960)); }
|
### Question:
IntegerDataItem implements DataItem { @Override public Long getLong() { return value.longValue(); } IntegerDataItem(); IntegerDataItem(final int value); @Override Boolean getBoolean(); @Override Byte getByte(); @Override Integer getInteger(); @Override Short getShort(); @Override Long getLong(); @Override String getString(); @Override Double getDouble(); @Override Comparable getComparable(); @Override int compareTo(final Object o); @Override boolean equals(final Object o); @Override int hashCode(); @Override void write(final DataOutput out); @Override void readFields(final DataInput in); @Override String toString(); @Override byte getThriftType(); }### Answer:
@Test(groups = "fast") public void testConvertToLong() throws Exception { Assert.assertEquals(value0.getLong(), Long.valueOf(0)); Assert.assertEquals(value1.getLong(), Long.valueOf(1)); Assert.assertEquals(value1000000.getLong(), Long.valueOf(1000000)); Assert.assertEquals(valueMinus1000000.getLong(), Long.valueOf(-1000000)); }
|
### Question:
EventHubCollector extends CollectorComponent { @Override public EventHubCollector start() { if (!closed.get()) lazyRegisterEventProcessorFactoryWithHost.get(); return this; } EventHubCollector(Builder builder); EventHubCollector(
LazyRegisterEventProcessorFactoryWithHost lazyRegisterEventProcessorFactoryWithHost); static Builder newBuilder(); @Override EventHubCollector start(); @Override CheckResult check(); @Override void close(); }### Answer:
@Test public void start_invokesRegistration() { EventHubCollector collector = new EventHubCollector(new LazyFuture()); collector.start(); assertThat(registration).isCompleted(); }
@Test public void start_registersOnlyOnce() { AtomicInteger registrations = new AtomicInteger(); EventHubCollector collector = new EventHubCollector( new LazyFuture() { @Override protected Future<?> compute() { registrations.incrementAndGet(); return super.compute(); } }); collector.start(); collector.start(); assertThat(registrations.get()).isEqualTo(1); }
|
### Question:
EventHubCollector extends CollectorComponent { @Override public CheckResult check() { try { Future<?> registrationFuture = lazyRegisterEventProcessorFactoryWithHost.get(); registrationFuture.get(); return CheckResult.OK; } catch (RuntimeException e) { return CheckResult.failed(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return CheckResult.failed(e); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof Error) throw (Error) cause; return CheckResult.failed(cause); } } EventHubCollector(Builder builder); EventHubCollector(
LazyRegisterEventProcessorFactoryWithHost lazyRegisterEventProcessorFactoryWithHost); static Builder newBuilder(); @Override EventHubCollector start(); @Override CheckResult check(); @Override void close(); }### Answer:
@Test public void check_invokesRegistration() { EventHubCollector collector = new EventHubCollector(new LazyFuture()); assertThat(collector.check().ok()).isTrue(); assertThat(registration).isCompleted(); }
@Test public void check_failsOnRuntimeException_registering() { RuntimeException exception = new RuntimeException(); EventHubCollector collector = new EventHubCollector( new LazyFuture() { @Override protected Future<?> compute() { throw exception; } }); CheckResult result = collector.check(); assertThat(result.error()).isEqualTo(exception); }
@Test public void check_failsOnRuntimeException_registration() { RuntimeException exception = new RuntimeException(); EventHubCollector collector = new EventHubCollector( new LazyFuture() { @Override protected Future<?> compute() { registration.completeExceptionally(exception); return registration; } }); CheckResult result = collector.check(); assertThat(result.error()).isEqualTo(exception); }
|
### Question:
EventHubCollector extends CollectorComponent { public static Builder newBuilder() { return new Builder(); } EventHubCollector(Builder builder); EventHubCollector(
LazyRegisterEventProcessorFactoryWithHost lazyRegisterEventProcessorFactoryWithHost); static Builder newBuilder(); @Override EventHubCollector start(); @Override CheckResult check(); @Override void close(); }### Answer:
@Test public void blobpathprefix_set_toaconstant_atstartup() { EventHubCollector.Builder builder1 = EventHubCollector.newBuilder(); EventHubCollector.Builder builder2 = EventHubCollector.newBuilder(); assertThat(builder2.storageBlobPrefix).isEqualTo(builder1.storageBlobPrefix); }
|
### Question:
LazyRegisterEventProcessorFactoryWithHost { Future<?> get() { if (future == null) { synchronized (this) { if (future == null) { future = compute(); } } } return future; } LazyRegisterEventProcessorFactoryWithHost(EventHubCollector.Builder builder); }### Answer:
@Test public void get_registersFactory() throws Exception { LazyRegisterEventProcessorFactoryWithHost lazy = new TestLazyRegisterEventProcessorFactoryWithHost(); lazy.get(); assertThat(registration).isCompleted(); }
@Test public void get_doesntWrapRuntimeException() throws Exception { RuntimeException exception = new RuntimeException("Failure initializing Storage lease manager"); LazyRegisterEventProcessorFactoryWithHost lazy = new TestLazyRegisterEventProcessorFactoryWithHost() { @Override Future<?> registerEventProcessorFactoryWithHost() throws Exception { throw exception; } }; thrown.expect(is(exception)); lazy.get(); }
@Test public void get_wrapsCheckedException() throws Exception { LazyRegisterEventProcessorFactoryWithHost lazy = new TestLazyRegisterEventProcessorFactoryWithHost() { @Override Future<?> registerEventProcessorFactoryWithHost() throws InvalidKeyException { throw new InvalidKeyException(); } }; thrown.expect(RuntimeException.class); thrown.expectCause(isA(InvalidKeyException.class)); lazy.get(); }
|
### Question:
Index { public static <K, V extends Enum<V>> @NonNull Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction) { return create(type, keyFunction, type.getEnumConstants()); } private Index(final Map<K, V> keyToValue, final Map<V, K> valueToKey); static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction); @SafeVarargs static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SafeVarargs @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull List<V> constants); @NonNull Set<K> keys(); @Nullable K key(final @NonNull V value); @NonNull Set<V> values(); @Nullable V value(final @NonNull K key); }### Answer:
@Test void testCreateWithNonUniqueKey() { assertThrows(IllegalStateException.class, () -> Index.create(NonUniqueThing.class, thing -> thing.name)); }
@Test void testCreateWithNonUniqueValue() { assertThrows(IllegalStateException.class, () -> Index.create(Thing.class, thing -> UUID.randomUUID().toString(), Thing.ABC, Thing.ABC)); }
|
### Question:
AbstractComponent implements Component, Examinable { @Override public final @NonNull List<Component> children() { return this.children; } protected AbstractComponent(final @NonNull List<? extends ComponentLike> children, final @NonNull Style style); @Override final @NonNull List<Component> children(); @Override final @NonNull Style style(); @Override @NonNull Component replaceText(final @NonNull Pattern pattern, final @NonNull Function<TextComponent.Builder, @Nullable ComponentLike> replacement, final @NonNull IntFunction2<PatternReplacementResult> fn); @Override boolean equals(final @Nullable Object other); @Override int hashCode(); @Override @NonNull Stream<? extends ExaminableProperty> examinableProperties(); @Override String toString(); }### Answer:
@Test void testRebuildEmptyChildren() { final C c0 = this.buildOne(); final B b0 = c0.toBuilder(); final C c1 = b0.build(); assertEquals(c0, c1); assertThat(c0.children()).isEmpty(); assertThat(c1.children()).isEmpty(); }
@Test void testBuilderApplyDeep() { final C c0 = this.builder() .append(Component.text("a", NamedTextColor.RED)) .append(Component.text("b", NamedTextColor.RED)) .applyDeep(builder -> builder.color(NamedTextColor.GREEN)) .build(); final List<Component> children = c0.children(); assertThat(children).hasSize(2); forEachTransformAndAssert(children, Component::color, color -> assertEquals(NamedTextColor.GREEN, color)); }
@Test void testChildren() { final C c0 = this.buildOne(); assertThat(c0.children()).isEmpty(); final Component child = Component.text("foo"); final Component c1 = c0.children(Collections.singletonList(child)); assertThat(c1.children()).containsExactly(child).inOrder(); }
|
### Question:
LinearComponents { private static IllegalStateException nothingComponentLike() { return new IllegalStateException("Cannot build component linearly - nothing component-like was given"); } private LinearComponents(); static @NonNull Component linear(final @NonNull ComponentBuilderApplicable@NonNull... applicables); }### Answer:
@Test void testNothingComponentLike() { assertThrows(IllegalStateException.class, () -> LinearComponents.linear(TextDecoration.BOLD)); assertThrows(IllegalStateException.class, () -> LinearComponents.linear(TextDecoration.BOLD, TextColor.color(0xaa0000))); }
|
### Question:
NamedTextColor implements TextColor { public static @NonNull NamedTextColor nearestTo(final @NonNull TextColor any) { if(any instanceof NamedTextColor) { return (NamedTextColor) any; } requireNonNull(any, "color"); int matchedDistance = Integer.MAX_VALUE; NamedTextColor match = VALUES.get(0); for(int i = 0, length = VALUES.size(); i < length; i++) { final NamedTextColor potential = VALUES.get(i); final int distance = distanceSquared(any, potential); if(distance < matchedDistance) { match = potential; matchedDistance = distance; } if(distance == 0) { break; } } return match; } private NamedTextColor(final String name, final int value); static @Nullable NamedTextColor ofExact(final int value); static @NonNull NamedTextColor nearestTo(final @NonNull TextColor any); @Override int value(); @Override @NonNull String toString(); static final NamedTextColor BLACK; static final NamedTextColor DARK_BLUE; static final NamedTextColor DARK_GREEN; static final NamedTextColor DARK_AQUA; static final NamedTextColor DARK_RED; static final NamedTextColor DARK_PURPLE; static final NamedTextColor GOLD; static final NamedTextColor GRAY; static final NamedTextColor DARK_GRAY; static final NamedTextColor BLUE; static final NamedTextColor GREEN; static final NamedTextColor AQUA; static final NamedTextColor RED; static final NamedTextColor LIGHT_PURPLE; static final NamedTextColor YELLOW; static final NamedTextColor WHITE; static final Index<String, NamedTextColor> NAMES; }### Answer:
@SuppressWarnings("ConstantConditions") @Test void testNullRejected() { assertThrows(NullPointerException.class, () -> NamedTextColor.nearestTo(null), "color"); }
|
### Question:
Index { public @Nullable K key(final @NonNull V value) { return this.valueToKey.get(value); } private Index(final Map<K, V> keyToValue, final Map<V, K> valueToKey); static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction); @SafeVarargs static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SafeVarargs @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull List<V> constants); @NonNull Set<K> keys(); @Nullable K key(final @NonNull V value); @NonNull Set<V> values(); @Nullable V value(final @NonNull K key); }### Answer:
@Test void testKey() { for(final Thing thing : Thing.values()) { assertEquals(thing.name, THINGS.key(thing)); } }
|
### Question:
Index { public @Nullable V value(final @NonNull K key) { return this.keyToValue.get(key); } private Index(final Map<K, V> keyToValue, final Map<V, K> valueToKey); static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction); @SafeVarargs static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SafeVarargs @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull List<V> constants); @NonNull Set<K> keys(); @Nullable K key(final @NonNull V value); @NonNull Set<V> values(); @Nullable V value(final @NonNull K key); }### Answer:
@Test void testValue() { for(final Thing thing : Thing.values()) { assertEquals(thing, THINGS.value(thing.name)); } }
|
### Question:
Index { public @NonNull Set<K> keys() { return Collections.unmodifiableSet(this.keyToValue.keySet()); } private Index(final Map<K, V> keyToValue, final Map<V, K> valueToKey); static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction); @SafeVarargs static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SafeVarargs @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull List<V> constants); @NonNull Set<K> keys(); @Nullable K key(final @NonNull V value); @NonNull Set<V> values(); @Nullable V value(final @NonNull K key); }### Answer:
@Test void testKeys() { assertThat(THINGS.keys()).containsExactly("abc", "def"); }
|
### Question:
Index { public @NonNull Set<V> values() { return Collections.unmodifiableSet(this.valueToKey.keySet()); } private Index(final Map<K, V> keyToValue, final Map<V, K> valueToKey); static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction); @SafeVarargs static Index<K, V> create(final Class<V> type, final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SafeVarargs @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull V@NonNull... values); @SuppressWarnings("RedundantTypeArguments") // explicit type parameters needed to fix build on JDK 1.8 static Index<K, V> create(final @NonNull Function<? super V, ? extends K> keyFunction, final @NonNull List<V> constants); @NonNull Set<K> keys(); @Nullable K key(final @NonNull V value); @NonNull Set<V> values(); @Nullable V value(final @NonNull K key); }### Answer:
@Test void testValues() { assertThat(THINGS.values()).containsExactly(Thing.ABC, Thing.DEF); }
|
### Question:
OrdersConnector { public OrderResponse chargeChard() { ResponseEntity<String> orderResponse = request(ordersHost, "/process-order"); return new OrderResponse(orderResponse); } @Autowired OrdersConnector(
@Value("${orders.host}") String ordersHost,
RestTemplate restTemplate
); OrderResponse chargeChard(); }### Answer:
@Test public void pingReturnsSuccess_whenSecondTraceSucceeds() throws Exception { doReturn(ResponseEntity.ok().build()).when(restTemplate).getForEntity("http: OrderResponse response = this.subject.chargeChard(); OrderResponse expectedResponse = new OrderResponse(true, "order processed successfully"); assertThat(response, equalTo(expectedResponse)); verify(restTemplate).getForEntity("http: }
@Test public void pingReturnsFailure_whenSecondTraceFails() throws Exception { doReturn(ResponseEntity.badRequest().body("invalid content")).when(restTemplate).getForEntity("http: OrderResponse response = this.subject.chargeChard(); OrderResponse expectedResponse = new OrderResponse(false, "unable to process order, please try again."); assertThat(response, equalTo(expectedResponse)); verify(restTemplate).getForEntity("http: }
|
### Question:
PaymentsConnector { public PaymentResponse chargeChard() { ResponseEntity<String> paymentResponse = request(paymentsHost, "/charge-card"); return new PaymentResponse(paymentResponse); } @Autowired PaymentsConnector(
@Value("${payments.host}") String paymentsHost,
RestTemplate restTemplate
); PaymentResponse chargeChard(); }### Answer:
@Test public void pingReturnsSuccess_whenSecondTraceSucceeds() throws Exception { doReturn(ResponseEntity.ok().build()).when(restTemplate).getForEntity("http: PaymentResponse response = this.subject.chargeChard(); PaymentResponse expectedResponse = new PaymentResponse(true, "order processed successfully"); assertThat(response, equalTo(expectedResponse)); verify(restTemplate).getForEntity("http: }
@Test public void pingReturnsFailure_whenSecondTraceFails() throws Exception { doReturn(ResponseEntity.badRequest().body("invalid content")).when(restTemplate).getForEntity("http: PaymentResponse response = this.subject.chargeChard(); PaymentResponse expectedResponse = new PaymentResponse(false, "unable to process order, please try again."); assertThat(response, equalTo(expectedResponse)); verify(restTemplate).getForEntity("http: }
|
### Question:
ImageComponent { public static String getWelcomeMap(boolean isSmall) { MapboxStaticImage client = new MapboxStaticImage.Builder() .setAccessToken(Constants.MAPBOX_ACCESS_TOKEN) .setWidth(isSmall ? smallWidth : largeWidth) .setHeight(isSmall ? smallHeight : largeHeight) .setStyleId(com.mapbox.services.Constants.MAPBOX_STYLE_SATELLITE) .setLat(0.0).setLon(0.0) .setZoom(0) .build(); return client.getUrl().toString(); } static String getWelcomeMap(boolean isSmall); static String getLocationMap(Position position, boolean isSmall); static String getRouteMap(Position origin, Position destination, String geometry, boolean isSmall); }### Answer:
@Test public void getWelcomeMapIsNotEmpty() { assertFalse(TextUtils.isEmpty(ImageComponent.getWelcomeMap(true))); assertTrue(ImageComponent.getWelcomeMap(true).startsWith(BASE_URL)); assertFalse(TextUtils.isEmpty(ImageComponent.getWelcomeMap(false))); assertTrue(ImageComponent.getWelcomeMap(false).startsWith(BASE_URL)); }
|
### Question:
ImageComponent { public static String getLocationMap(Position position, boolean isSmall) { StaticMarkerAnnotation marker = new StaticMarkerAnnotation.Builder() .setName(com.mapbox.services.Constants.PIN_LARGE) .setPosition(position) .setColor(COLOR_RED) .build(); MapboxStaticImage client = new MapboxStaticImage.Builder() .setAccessToken(Constants.MAPBOX_ACCESS_TOKEN) .setWidth(isSmall ? smallWidth : largeWidth) .setHeight(isSmall ? smallHeight : largeHeight) .setStyleId(com.mapbox.services.Constants.MAPBOX_STYLE_STREETS) .setPosition(position) .setStaticMarkerAnnotations(marker) .setZoom(15) .build(); return client.getUrl().toString(); } static String getWelcomeMap(boolean isSmall); static String getLocationMap(Position position, boolean isSmall); static String getRouteMap(Position origin, Position destination, String geometry, boolean isSmall); }### Answer:
@Test public void getLocationMapIsNotEmpty() { Position whiteHouse = Position.fromCoordinates(-77.0365, 38.8977); assertTrue(ImageComponent.getLocationMap(whiteHouse, true).startsWith(BASE_URL)); assertTrue(ImageComponent.getLocationMap(whiteHouse, false).startsWith(BASE_URL)); }
|
### Question:
OkHttpCall implements Call<T> { @Override public T execute() throws IOException, ApiError { Response response = rawCall.execute(); return adapt(response); } OkHttpCall(okhttp3.Call rawCall, ResponseAdapter<T> adapter); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") @Override OkHttpCall<T> clone(); }### Answer:
@Test public void execute_CallsDelegateMethod() throws Exception { testCall.execute(); verify(mockOkHttpCall).execute(); }
@Test public void execute_PassesThrownExceptions() throws Exception { IOException error = new IOException(); doThrow(error).when(mockOkHttpCall).execute(); expectedException.expect(is(error)); testCall.execute(); ApiError apiError = new ApiError(5000, ""); doThrow(apiError).when(mockOkHttpCall).execute(); expectedException.expect(is(apiError)); testCall.execute(); }
|
### Question:
ExecutorProgressListener implements ProgressListener, Runnable { @Override public void onProgress(long done, long total) { if (!pending || done == total) { this.done = done; this.total = total; try { pending = true; executor.execute(this); } catch (RejectedExecutionException ignored) { pending = false; } } } ExecutorProgressListener(ProgressListener delegate, Executor executor); @Override void run(); @Override void onProgress(long done, long total); }### Answer:
@Test public void onProgress_Schedules_Once_Until_DelegateGetsNotified() throws Exception { testListener.onProgress(1, 1000); verify(targetExecutor).execute(any(Runnable.class)); testListener.onProgress(2, 1000); verifyNoMoreInteractions(targetExecutor); }
@Test public void onProgress_CallsDelegateMethodOnAnotherThread() throws Exception { testListener.onProgress(1, 1000); verifyZeroInteractions(delegateListener); verify(targetExecutor).execute(any(Runnable.class)); }
|
### Question:
ScheduledCall implements Call<T> { @Override public T execute() throws IOException, ApiError { return delegate.execute(); } ScheduledCall(Call<T> delegate, Executor callbackExecutor); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override ScheduledCall<T> clone(); }### Answer:
@Test public void execute_CallsDelegateMethod() throws Exception { testCall.execute(); verify(wrappedCall).execute(); }
@Test public void execute_PassesThrownExceptions() throws Exception { IOException error = new IOException(); doThrow(error).when(wrappedCall).execute(); expectedException.expect(is(error)); testCall.execute(); ApiError apiError = new ApiError(5000, ""); doThrow(apiError).when(wrappedCall).execute(); expectedException.expect(is(apiError)); testCall.execute(); }
|
### Question:
ScheduledCall implements Call<T> { @Override public void cancel() { delegate.cancel(); } ScheduledCall(Call<T> delegate, Executor callbackExecutor); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override ScheduledCall<T> clone(); }### Answer:
@Test public void cancel_CallsDelegateMethod() throws Exception { testCall.cancel(); verify(wrappedCall).cancel(); }
|
### Question:
ScheduledCall implements Call<T> { @Override public boolean isExecuted() { return delegate.isExecuted(); } ScheduledCall(Call<T> delegate, Executor callbackExecutor); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override ScheduledCall<T> clone(); }### Answer:
@SuppressWarnings("ConstantConditions") @Test public void isExecuted_ReturnsDelegateState() throws Exception { boolean expectedValue = true; when(wrappedCall.isExecuted()).thenReturn(expectedValue); boolean actualValue = testCall.isExecuted(); verify(wrappedCall).isExecuted(); assertEquals(actualValue, expectedValue); }
|
### Question:
ScheduledCall implements Call<T> { @Override public boolean isCanceled() { return delegate.isCanceled(); } ScheduledCall(Call<T> delegate, Executor callbackExecutor); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override ScheduledCall<T> clone(); }### Answer:
@SuppressWarnings("ConstantConditions") @Test public void isCancelled_ReturnsDelegateState() throws Exception { boolean expectedValue = true; when(wrappedCall.isCanceled()).thenReturn(expectedValue); boolean actualValue = testCall.isCanceled(); verify(wrappedCall).isCanceled(); assertEquals(actualValue, expectedValue); }
|
### Question:
ScheduledCall implements Call<T> { @Override public void enqueue(final Callback<T> callback) { if (callback == null) { throw new IllegalArgumentException("Callback argument cannot be null."); } delegate.enqueue(new Callback<T>() { @Override public void onResponse(Call<T> call, final T response) { callbackExecutor.execute(new Runnable() { @Override public void run() { callback.onResponse(ScheduledCall.this, response); } }); } @Override public void onFailure(Call<T> call, final Throwable t) { callbackExecutor.execute(new Runnable() { @Override public void run() { callback.onFailure(ScheduledCall.this, t); } }); } }); } ScheduledCall(Call<T> delegate, Executor callbackExecutor); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override ScheduledCall<T> clone(); }### Answer:
@Test public void enqueue_Throws_WithNullArgument() throws Exception { expectedException.expect(IllegalArgumentException.class); testCall.enqueue(null); }
@Test public void enqueue_CallsDelegateMethodWithNonNullArgument() throws Exception { testCall.enqueue(testCallback); verify(wrappedCall).enqueue(callbackArgumentCaptor.capture()); Callback passedCallback = callbackArgumentCaptor.getValue(); assertNotNull(passedCallback); }
|
### Question:
ScheduledCall implements Call<T> { @SuppressWarnings("CloneDoesntCallSuperClone") @Override public ScheduledCall<T> clone() { return new ScheduledCall<>(delegate.clone(), callbackExecutor); } ScheduledCall(Call<T> delegate, Executor callbackExecutor); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") // Performing deep clone. @Override ScheduledCall<T> clone(); }### Answer:
@Test public void clone_ReturnsNewObject() throws Exception { Call<Object> clonedObject = testCall.clone(); assertNotNull(clonedObject); assertNotEquals(testCall, clonedObject); }
|
### Question:
OkHttpCall implements Call<T> { @Override public void cancel() { rawCall.cancel(); } OkHttpCall(okhttp3.Call rawCall, ResponseAdapter<T> adapter); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") @Override OkHttpCall<T> clone(); }### Answer:
@Test public void cancel_CallsDelegateMethod() throws Exception { testCall.cancel(); verify(mockOkHttpCall).cancel(); }
|
### Question:
OkHttpCall implements Call<T> { @Override public boolean isExecuted() { return rawCall.isExecuted(); } OkHttpCall(okhttp3.Call rawCall, ResponseAdapter<T> adapter); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") @Override OkHttpCall<T> clone(); }### Answer:
@SuppressWarnings("ConstantConditions") @Test public void isExecuted_ReturnsDelegateState() throws Exception { boolean expectedValue = true; when(mockOkHttpCall.isExecuted()).thenReturn(expectedValue); boolean actualValue = testCall.isExecuted(); verify(mockOkHttpCall).isExecuted(); assertEquals(actualValue, expectedValue); }
|
### Question:
OkHttpCall implements Call<T> { @Override public boolean isCanceled() { return rawCall.isCanceled(); } OkHttpCall(okhttp3.Call rawCall, ResponseAdapter<T> adapter); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") @Override OkHttpCall<T> clone(); }### Answer:
@SuppressWarnings("ConstantConditions") @Test public void isCancelled_ReturnsDelegateState() throws Exception { boolean expectedValue = true; when(mockOkHttpCall.isCanceled()).thenReturn(expectedValue); boolean actualValue = testCall.isCanceled(); verify(mockOkHttpCall).isCanceled(); assertEquals(actualValue, expectedValue); }
|
### Question:
OkHttpCall implements Call<T> { @Override public void enqueue(final Callback<T> callback) { if (callback == null) { throw new IllegalArgumentException("Callback argument cannot be null."); } rawCall.enqueue(new okhttp3.Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { callback.onFailure(OkHttpCall.this, e); } @Override public void onResponse(okhttp3.Call call, Response response) throws IOException { try { callback.onResponse(OkHttpCall.this, adapt(response)); } catch (ApiError | IOException e) { closeQuietly(response); callback.onFailure(OkHttpCall.this, e); } } }); } OkHttpCall(okhttp3.Call rawCall, ResponseAdapter<T> adapter); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") @Override OkHttpCall<T> clone(); }### Answer:
@Test public void enqueue_Throws_WithNullArgument() throws Exception { expectedException.expect(IllegalArgumentException.class); testCall.enqueue(null); }
@Test public void enqueue_CallsDelegateMethodWithNonNullArgument() throws Exception { testCall.enqueue(testCallback); verify(mockOkHttpCall).enqueue(callbackArgumentCaptor.capture()); okhttp3.Callback passedCallback = callbackArgumentCaptor.getValue(); assertNotNull(passedCallback); }
@Test public void enqueue_CallsFailureMethod_OnDelegateFailureCalled() throws Exception { testCall.enqueue(testCallback); verify(mockOkHttpCall).enqueue(callbackArgumentCaptor.capture()); okhttp3.Callback passedCallback = callbackArgumentCaptor.getValue(); assertNotNull(passedCallback); IOException error = new IOException("something wrong"); passedCallback.onFailure(mockOkHttpCall, error); verify(testCallback).onFailure(eq(testCall), eq(error)); }
|
### Question:
OkHttpCall implements Call<T> { @SuppressWarnings("CloneDoesntCallSuperClone") @Override public OkHttpCall<T> clone() { return new OkHttpCall<>(rawCall.clone(), responseAdapter); } OkHttpCall(okhttp3.Call rawCall, ResponseAdapter<T> adapter); @Override T execute(); @Override void enqueue(final Callback<T> callback); @Override boolean isExecuted(); @Override void cancel(); @Override boolean isCanceled(); @SuppressWarnings("CloneDoesntCallSuperClone") @Override OkHttpCall<T> clone(); }### Answer:
@Test public void clone_ReturnsNewObject() throws Exception { Call<Object> clonedObject = testCall.clone(); assertNotNull(clonedObject); assertNotEquals(testCall, clonedObject); }
|
### Question:
UserService { public void register(User user) throws UserExistException{ User u = this.getUserByUserName(user.getUserName()); if(u != null){ throw new UserExistException("用户名已经存在"); }else{ user.setCredit(100); user.setUserType(1); userDao.save(user); } } @Autowired void setUserDao(UserDao userDao); @Autowired void setLoginLogDao(LoginLogDao loginLogDao); void register(User user); void update(User user); User getUserByUserName(String userName); User getUserById(int userId); void lockUser(String userName); void unlockUser(String userName); List<User> queryUserByUserName(String userName); List<User> getAllUsers(); void loginSuccess(User user); }### Answer:
@Test public void register() throws UserExistException{ User user = new User(); user.setUserName("tom"); user.setPassword("1234"); doAnswer(new Answer<User>() { public User answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); User user = (User) args[0]; if (user != null) { user.setUserId(1); } return user; } }).when(userDao).save(user); userService.register(user); assertEquals(user.getUserId(), 1); verify(userDao, times(1)).save(user); }
|
### Question:
ForumService { public void addBoardManager(int boardId,String userName){ User user = userDao.getUserByUserName(userName); if(user == null){ throw new RuntimeException("用户名为"+userName+"的用户不存在。"); }else{ Board board = boardDao.get(boardId); user.getManBoards().add(board); userDao.update(user); } } @Autowired void setTopicDao(TopicDao topicDao); @Autowired void setUserDao(UserDao userDao); @Autowired void setBoardDao(BoardDao boardDao); @Autowired void setPostDao(PostDao postDao); void addTopic(Topic topic); void removeTopic(int topicId); void addPost(Post post); void removePost(int postId); void addBoard(Board board); void removeBoard(int boardId); void makeDigestTopic(int topicId); List<Board> getAllBoards(); Page getPagedTopics(int boardId,int pageNo,int pageSize); Page getPagedPosts(int topicId,int pageNo,int pageSize); Page queryTopicByTitle(String title,int pageNo,int pageSize); Board getBoardById(int boardId); Topic getTopicByTopicId(int topicId); Post getPostByPostId(int postId); void addBoardManager(int boardId,String userName); void updateTopic(Topic topic); void updatePost(Post post); }### Answer:
@Test @DataSet("XiaoChun.DataSet.xls") public void addBoardManager(){ forumService.addBoardManager(1,"tom"); User userDb = userService.getUserByUserName("tom"); assertEquals(userDb.getManBoards().size(), greaterThan(0)); }
|
### Question:
ForumDao { public void addForums(final List<Forum> forums) { final String sql = "INSERT INTO t_forum(forum_name,forum_desc) VALUES(?,?)"; jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { public int getBatchSize() { return forums.size(); } public void setValues(PreparedStatement ps, int index) throws SQLException { Forum forum = forums.get(index); ps.setString(1, forum.getForumName()); ps.setString(2, forum.getForumDesc()); } }); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); @Autowired void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate); void initDb(); void addForum(final Forum forum); void addForumByNamedParams(final Forum forum); void addForums(final List<Forum> forums); Forum getForum(final int forumId); List<Forum> getForums(final int fromId, final int toId); }### Answer:
@Test public void testAddForums() throws Throwable { List<Forum> forums = new ArrayList<Forum>(); for(int i =0 ;i< 100000 ;i++){ Forum f1 = new Forum(); f1.setForumName("爱美妈妈"); f1.setForumDesc("减肥、塑身、化妆品"); forums.add(f1); } forumDao.addForums(forums); }
|
### Question:
ForumDao { public void addForum(final Forum forum) { final String sql = "INSERT INTO t_forum(forum_name,forum_desc) VALUES(?,?)"; Object[] params = new Object[] { forum.getForumName(), forum.getForumDesc() }; KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection conn) throws SQLException { PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, forum.getForumName()); ps.setString(2, forum.getForumDesc()); return ps; } }, keyHolder); forum.setForumId(keyHolder.getKey().intValue()); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); @Autowired void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate); void initDb(); void addForum(final Forum forum); void addForumByNamedParams(final Forum forum); void addForums(final List<Forum> forums); Forum getForum(final int forumId); List<Forum> getForums(final int fromId, final int toId); }### Answer:
@Test public void testAddForum() { Forum forum = new Forum(); forum.setForumName("1二手市场"); forum.setForumDesc("1二手货物的交流论坛。"); forumDao.addForum(forum); System.out.println(forum.getForumId()); }
|
### Question:
ForumDao { public void addForumByNamedParams(final Forum forum) { final String sql = "INSERT INTO t_forum(forum_name, forum_desc) VALUES(:forumName,:forumDesc)"; SqlParameterSource sps = new BeanPropertySqlParameterSource(forum); namedParameterJdbcTemplate.update(sql, sps); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); @Autowired void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate); void initDb(); void addForum(final Forum forum); void addForumByNamedParams(final Forum forum); void addForums(final List<Forum> forums); Forum getForum(final int forumId); List<Forum> getForums(final int fromId, final int toId); }### Answer:
@Test public void testAddForumByNamedParams() { Forum forum = new Forum(); forum.setForumName("2二手市场"); forum.setForumDesc("2二手货物的交流论坛。"); forumDao.addForumByNamedParams(forum); }
|
### Question:
ForumOODao { public Forum getForum(int forumId){ return forumQuery.findObject(forumId); } @Autowired void setDataSource(DataSource dataSource); @PostConstruct void init(); Forum getForum(int forumId); void addForum(Forum forum); int getTopicNum(int userId); int getForumNum(); }### Answer:
@Test public void testGetForum(){ jdbcTemplate.execute(" insert into t_forum(forum_name,forum_desc) "+ " values('test','test')"); int forumId = jdbcTemplate.queryForObject("select max(forum_id) from t_forum",Integer.class); Forum forum = forumDao.getForum(forumId); System.out.println(forum.getForumName()); }
|
### Question:
ForumOODao { public void addForum(Forum forum){ forumInsert.insert(forum); } @Autowired void setDataSource(DataSource dataSource); @PostConstruct void init(); Forum getForum(int forumId); void addForum(Forum forum); int getTopicNum(int userId); int getForumNum(); }### Answer:
@Test public void testAddForum(){ Forum forum = new Forum(); forum.setForumName("test2"); forum.setForumDesc("desc 2"); forumDao.addForum(forum); }
|
### Question:
ForumOODao { public int getTopicNum(int userId){ return getTopicNum.getTopicNum(userId); } @Autowired void setDataSource(DataSource dataSource); @PostConstruct void init(); Forum getForum(int forumId); void addForum(Forum forum); int getTopicNum(int userId); int getForumNum(); }### Answer:
@Test public void testGetTopicNum(){ int topicNum = forumDao.getTopicNum(1); System.out.println("topicNum:"+topicNum); }
|
### Question:
PostDao { public void addPost(final Post post){ String sql = " INSERT INTO t_post(post_id,user_id,post_text,post_attach)" + " VALUES(?,?,?,?)"; jdbcTemplate.execute(sql,new AbstractLobCreatingPreparedStatementCallback(this.lobHandler) { protected void setValues(PreparedStatement ps,LobCreator lobCreator) throws SQLException { ps.setInt(1, incre.nextIntValue()); ps.setInt(2, post.getUserId()); lobCreator.setClobAsString(ps, 3, post.getPostText()); lobCreator.setBlobAsBytes(ps, 4, post.getPostAttach()); } }); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); @Autowired void setLobHandler(LobHandler lobHandler); @Autowired void setIncre(DataFieldMaxValueIncrementer incre); void addPost(final Post post); void getNativeConn(); List<Post> getAttachs(final int userId); void getAttach(final int postId, final OutputStream os); }### Answer:
@Test public void testAddPost() throws Throwable{ Post post = new Post(); post.setUserId(2); ClassPathResource res = new ClassPathResource("temp.jpg"); byte[] mockImg = FileCopyUtils.copyToByteArray(res.getFile()); post.setPostAttach(mockImg); post.setPostText("测试帖子的内容"); postDao.addPost(post); }
|
### Question:
PostDao { public void getAttach(final int postId, final OutputStream os) { String sql = "SELECT post_attach FROM t_post WHERE post_id=? "; jdbcTemplate.query(sql, new Object[] {postId}, new AbstractLobStreamingResultSetExtractor() { protected void handleNoRowFound() throws LobRetrievalFailureException { System.out.println("Not Found result!"); } public void streamData(ResultSet rs) throws SQLException,IOException { InputStream is = lobHandler.getBlobAsBinaryStream(rs, 1); if (is != null) { FileCopyUtils.copy(is, os); } } } ); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); @Autowired void setLobHandler(LobHandler lobHandler); @Autowired void setIncre(DataFieldMaxValueIncrementer incre); void addPost(final Post post); void getNativeConn(); List<Post> getAttachs(final int userId); void getAttach(final int postId, final OutputStream os); }### Answer:
@Test public void testgetAttach() throws Throwable{ FileOutputStream fos = new FileOutputStream("d:/temp.jpg"); postDao.getAttach(1,fos); }
|
### Question:
UserService { public User getUserByUserName(String userName){ return userDao.getUserByUserName(userName); } @Autowired void setUserDao(UserDao userDao); @Autowired void setLoginLogDao(LoginLogDao loginLogDao); void register(User user); void update(User user); User getUserByUserName(String userName); User getUserById(int userId); void lockUser(String userName); void unlockUser(String userName); List<User> queryUserByUserName(String userName); List<User> getAllUsers(); void loginSuccess(User user); }### Answer:
@Test public void getUserByUserName() { User user = new User(); user.setUserName("tom"); user.setPassword("1234"); user.setCredit(100); doReturn(user).when(userDao).getUserByUserName("tom"); User u = userService.getUserByUserName("tom"); assertNotNull(u); assertEquals(u.getUserName(), user.getUserName()); verify(userDao, times(1)).getUserByUserName("tom"); }
|
### Question:
PostDao { public List<Post> getAttachs(final int userId) { String sql = " SELECT post_id,post_attach FROM t_post where user_id =? and post_attach is not null "; return jdbcTemplate.query(sql, new Object[] { userId }, new RowMapper<Post>() { public Post mapRow(ResultSet rs, int rowNum) throws SQLException { int postId = rs.getInt(1); byte[] attach = lobHandler.getBlobAsBytes(rs, 2); Post post = new Post(); post.setPostId(postId); post.setPostAttach(attach); return post; } }); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); @Autowired void setLobHandler(LobHandler lobHandler); @Autowired void setIncre(DataFieldMaxValueIncrementer incre); void addPost(final Post post); void getNativeConn(); List<Post> getAttachs(final int userId); void getAttach(final int postId, final OutputStream os); }### Answer:
@Test public void testgetAttachs() throws Throwable{ Post post = new Post(); post.setUserId(2); ClassPathResource res = new ClassPathResource("temp.jpg"); byte[] mockImg = FileCopyUtils.copyToByteArray(res.getFile()); post.setPostAttach(mockImg); post.setPostText("测试帖子的内容"); postDao.addPost(post); List<Post> list = postDao.getAttachs(3); for (Post tempPost:list) { System.out.println(tempPost.getPostId()+";"+post.getPostAttach().length); } }
|
### Question:
TopicDao { public double getReplyRate(int userId) { String sql = "SELECT topic_replies,topic_views FROM t_topic WHERE user_id=?"; double rate = jdbcTemplate.queryForObject(sql, new Object[] { userId }, new RowMapper<Double>() { public Double mapRow(ResultSet rs, int index) throws SQLException { int replies = rs.getInt("topic_replies"); int views = rs.getInt("topic_views"); if (views > 0) return new Double((double) replies / views); else return new Double(0.0); } }); return rate; } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); double getReplyRate(int userId); int getUserTopicNum(final int userId); int getUserTopicNum2(int userId); SqlRowSet getTopicRowSet(int userId); }### Answer:
@Test public void testGetReplyRate() { double rate = topicDao.getReplyRate(2); System.out.println("rate is:" + rate); }
|
### Question:
TopicDao { public int getUserTopicNum(final int userId) { String sql = "{call P_GET_TOPIC_NUM(?,?)}"; CallableStatementCreatorFactory fac = new CallableStatementCreatorFactory(sql); fac.addParameter(new SqlParameter("userId",Types.INTEGER)); fac.addParameter(new SqlOutParameter("topicNum",Types.INTEGER)); Map<String,Integer> paramsMap = new HashMap<String,Integer>(); paramsMap.put("userId",userId); CallableStatementCreator csc = fac.newCallableStatementCreator (paramsMap); Integer num = jdbcTemplate.execute(csc,new CallableStatementCallback<Integer>(){ public Integer doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException { cs.execute(); return cs.getInt(2); } }); return num; } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); double getReplyRate(int userId); int getUserTopicNum(final int userId); int getUserTopicNum2(int userId); SqlRowSet getTopicRowSet(int userId); }### Answer:
@Test public void testGetUserTopicNum() throws Throwable { int num = topicDao.getUserTopicNum(1); System.out.println("num is:" + num); }
|
### Question:
TopicDao { public SqlRowSet getTopicRowSet(int userId) { String sql = "SELECT topic_id,topic_title FROM t_topic WHERE user_id=?"; return jdbcTemplate.queryForRowSet(sql,userId); } @Autowired void setJdbcTemplate(JdbcTemplate jdbcTemplate); double getReplyRate(int userId); int getUserTopicNum(final int userId); int getUserTopicNum2(int userId); SqlRowSet getTopicRowSet(int userId); }### Answer:
@Test public void testGetTopicRowSet() { SqlRowSet srs = topicDao.getTopicRowSet(1); while (srs.next()) { System.out.println(srs.getString("topic_id")); } }
|
### Question:
LoginController { @RequestMapping(value = "/loginCheck.html") public ModelAndView loginCheck(HttpServletRequest request){ User user = new User(); user.setUserName(request.getParameter("userName")); user.setPassword(request.getParameter("password")); boolean isValidUser = userService.hasMatchUser(user.getUserName(), user.getPassword()); if (!isValidUser) { return new ModelAndView("login", "error", "用户名或密码错误。"); } else { user = userService.findUserByUserName(user .getUserName()); user.setLastIp(request.getLocalAddr()); user.setLastVisit(new Date()); userService.loginSuccess(user); request.getSession().setAttribute("user", user); return new ModelAndView("main"); } } @RequestMapping(value = "/index.html") String loginPage(); @RequestMapping(value = "/loginCheck.html") ModelAndView loginCheck(HttpServletRequest request); @Autowired void setUserService(UserService userService); }### Answer:
@Test public void loginCheckByMock() throws Exception { request.setRequestURI("/loginCheck.html"); request.addParameter("userName", "tom"); request.addParameter("password", "123456"); ModelAndView mav = controller.loginCheck(request); User user = (User) request.getSession().getAttribute("user"); assertNotNull(mav); assertEquals(mav.getViewName(), "main"); assertNotNull(user); assertThat(user.getUserName(), equalTo("tom")); assertThat(user.getCredit(), greaterThan(5)); }
|
### Question:
MailSender implements ApplicationContextAware { public void sendMail(String to){ System.out.println("MailSender:模拟发送邮件..."); MailSendEvent mse = new MailSendEvent(this.ctx,to); ctx.publishEvent(mse); } void setApplicationContext(ApplicationContext ctx); void sendMail(String to); }### Answer:
@Test public void testMailSender() { MailSender mailSender = (MailSender)ctx.getBean("mailSender"); mailSender.sendMail("[email protected]"); }
|
### Question:
UserService { public boolean hasMatchUser(String userName, String password) { int matchCount =userDao.getMatchCount(userName, password); return matchCount > 0; } boolean hasMatchUser(String userName, String password); User findUserByUserName(String userName); @Transactional void loginSuccess(User user); @Autowired void setUserDao(UserDao userDao); @Autowired void setLoginLogDao(LoginLogDao loginLogDao); }### Answer:
@Test public void testHasMatchUser() { boolean b1 = userService.hasMatchUser("admin", "123456"); boolean b2 = userService.hasMatchUser("admin", "1111"); assertTrue(b1); assertTrue(!b2); }
|
### Question:
UserService { public User findUserByUserName(String userName) { return userDao.findUserByUserName(userName); } boolean hasMatchUser(String userName, String password); User findUserByUserName(String userName); @Transactional void loginSuccess(User user); @Autowired void setUserDao(UserDao userDao); @Autowired void setLoginLogDao(LoginLogDao loginLogDao); }### Answer:
@Test public void testFindUserByUserName()throws Exception{ for(int i =0; i< 100;i++) { User user = userService.findUserByUserName("admin"); assertEquals(user.getUserName(), "admin"); } }
|
### Question:
CastorSample { public static void objectToXml() { try { User user = getUser(); FileWriter writer = new FileWriter("out/CastorSampe.xml"); Mapping mapping = new Mapping(); String mappingFile = ResourceUtils.getResourceFullPath( CastorSample.class, "mapping.xml"); mapping.loadMapping(mappingFile); Marshaller marshaller = new Marshaller(writer); marshaller.setMapping(mapping); marshaller.setEncoding("GBK"); marshaller.marshal(user); } catch (Exception e) { e.printStackTrace(System.err); } } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String[] args); }### Answer:
@Test public void objectToXml()throws Exception { CastorSample.objectToXml(); FileReader reader = new FileReader("out/CastorSampe.xml"); BufferedReader br = new BufferedReader(reader); StringBuffer sb = new StringBuffer(""); String s; while ((s = br.readLine()) != null) { sb.append(s); } reader.close(); br.close(); assertXpathExists(" assertXpathExists(" assertXpathExists(" assertXpathExists(" }
|
### Question:
CastorSample { public static User xmlToObject() { try { FileReader reader = new FileReader("out/CastorSampe.xml"); Mapping mapping = new Mapping(); String mappingFile = ResourceUtils.getResourceFullPath( CastorSample.class, "mapping.xml"); mapping.loadMapping(mappingFile); Unmarshaller unmar = new Unmarshaller(mapping); User u = (User) unmar.unmarshal(reader); System.out.println("用户名: " + u.getUserName()); for (LoginLog log : u.getLogs()) { System.out.println("访问IP: " + log.getIp()); System.out.println("访问时间: " + log.getLoginDate()); } return u; } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(System.err); } return null; } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String[] args); }### Answer:
@Test public void xmlToObject() { CastorSample.objectToXml(); User u = CastorSample.xmlToObject(); assertNotNull(u); assertEquals("castor", u.getUserName()); for (LoginLog log : u.getLogs()) { assertNotNull(log); assertNotNull(log.getIp()); assertNotNull(log.getLoginDate()); } }
|
### Question:
UserService { public void lockUser(String userName){ User user = userDao.getUserByUserName(userName); user.setLocked(User.USER_LOCK); userDao.update(user); } @Autowired void setUserDao(UserDao userDao); @Autowired void setLoginLogDao(LoginLogDao loginLogDao); void register(User user); void update(User user); User getUserByUserName(String userName); User getUserById(int userId); void lockUser(String userName); void unlockUser(String userName); List<User> queryUserByUserName(String userName); List<User> getAllUsers(); void loginSuccess(User user); }### Answer:
@Test public void lockUser() { User user = new User(); user.setUserName("tom"); user.setPassword("1234"); doReturn(user).when(userDao).getUserByUserName("tom"); doNothing().when(userDao).update(user); userService.lockUser("tom"); User u = userService.getUserByUserName("tom"); assertEquals(User.USER_LOCK, u.getLocked()); }
|
### Question:
JibxSample { public static void objectToXml() { try { User user = getUser(); IBindingFactory bfact = BindingDirectory.getFactory(User.class); IMarshallingContext ctx = bfact.createMarshallingContext(); FileOutputStream outputStream = new FileOutputStream("out/JibxSample.xml"); ctx.marshalDocument(user, "UTF-8", null, outputStream); } catch (Exception ex) { ex.printStackTrace(); } } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String[] args); }### Answer:
@Test public void objectToXml()throws Exception { JibxSample.objectToXml(); }
|
### Question:
JibxSample { public static User xmlToObject(){ try { IBindingFactory bfact = BindingDirectory.getFactory(User.class); IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); File dataFile = new File("JibxSample.xml"); InputStream in = new FileInputStream(dataFile); User user = (User) uctx.unmarshalDocument(in, null); System.out.println("userName:" + user.getUserName()); for (LoginLog log : user.getLogs()) { if (log != null) { System.out.println("访问IP: " + log.getIp()); System.out.println("访问时间: " + log.getLoginDate()); } } return user; }catch (Exception e){ return null; } } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String[] args); }### Answer:
@Test public void xmlToObject() throws Exception { JibxSample.xmlToObject(); User u = JibxSample.xmlToObject(); }
|
### Question:
XStreamSample { public static void objectToXml() throws Exception { User user = getUser(); FileOutputStream outputStream = new FileOutputStream("out/XStreamSample.xml"); xstream.toXML(user, outputStream); } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String[] args); }### Answer:
@Test public void objectToXml()throws Exception { XStreamSample.objectToXml(); FileReader reader = new FileReader("out/XStreamSample.xml"); BufferedReader br = new BufferedReader(reader); StringBuffer sb = new StringBuffer(""); String s; while ((s = br.readLine()) != null) { sb.append(s); } System.out.println(sb.toString()); reader.close(); br.close(); assertXpathExists(" assertXpathExists(" assertXpathExists(" assertXpathExists(" }
|
### Question:
XStreamSample { public static User xmlToObject() throws Exception { FileInputStream fis = new FileInputStream("out/XStreamSample.xml"); User u = (User) xstream.fromXML(fis); for (LoginLog log : u.getLogs()) { if (log != null) { System.out.println("访问IP: " + log.getIp()); System.out.println("访问时间: " + log.getLoginDate()); } } return u; } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String[] args); }### Answer:
@Test public void xmlToObject()throws Exception { XStreamSample.objectToXml(); User u = XStreamSample.xmlToObject(); assertNotNull(u); assertEquals("xstream", u.getUserName()); for (LoginLog log : u.getLogs()) { assertNotNull(log); assertNotNull(log.getIp()); assertNotNull(log.getLoginDate()); } }
|
### Question:
JaxbSample { public static void objectToXml() throws Exception { User user = getUser(); JAXBContext context = JAXBContext.newInstance(User.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); FileWriter writer = new FileWriter("out/JaxbSample.xml"); m.marshal(user, writer); } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String args[]); }### Answer:
@Test public void objectToXml()throws Exception { JaxbSample.objectToXml(); }
|
### Question:
JaxbSample { public static User xmlToObject() throws Exception { JAXBContext context = JAXBContext.newInstance(User.class); FileReader reader = new FileReader("out/JaxbSample.xml"); Unmarshaller um = context.createUnmarshaller(); User u = (User) um.unmarshal(reader); for (LoginLog log : u.getLogs().getLoginLog()) { if (log != null) { System.out.println("访问IP: " + log.getIp()); System.out.println("访问时间: " + log.getLoginDate().getTime()); } } return u; } static User getUser(); static void objectToXml(); static User xmlToObject(); static void main(String args[]); }### Answer:
@Test public void xmlToObject()throws Exception { JaxbSample.objectToXml(); User u = JaxbSample.xmlToObject(); assertNotNull(u); assertEquals("jaxb", u.getUserName()); for (LoginLog log : u.getLogs().getLoginLog()) { assertNotNull(log); assertNotNull(log.getIp()); assertNotNull(log.getLoginDate()); } }
|
### Question:
UserService { public void unlockUser(String userName){ User user = userDao.getUserByUserName(userName); user.setLocked(User.USER_UNLOCK); userDao.update(user); } @Autowired void setUserDao(UserDao userDao); @Autowired void setLoginLogDao(LoginLogDao loginLogDao); void register(User user); void update(User user); User getUserByUserName(String userName); User getUserById(int userId); void lockUser(String userName); void unlockUser(String userName); List<User> queryUserByUserName(String userName); List<User> getAllUsers(); void loginSuccess(User user); }### Answer:
@Test public void unlockUser() { User user = new User(); user.setUserName("tom"); user.setPassword("1234"); user.setLocked(User.USER_LOCK); doReturn(user).when(userDao).getUserByUserName("tom"); doNothing().when(userDao).update(user); userService.unlockUser("tom"); User u = userService.getUserByUserName("tom"); assertEquals(User.USER_UNLOCK, u.getLocked()); }
|
### Question:
ForumService { public void addBoard(Board board) { boardDao.save(board); } @Autowired void setTopicDao(TopicDao topicDao); @Autowired void setUserDao(UserDao userDao); @Autowired void setBoardDao(BoardDao boardDao); @Autowired void setPostDao(PostDao postDao); void addTopic(Topic topic); void removeTopic(int topicId); void addPost(Post post); void removePost(int postId); void addBoard(Board board); void removeBoard(int boardId); void makeDigestTopic(int topicId); List<Board> getAllBoards(); Page getPagedTopics(int boardId,int pageNo,int pageSize); Page getPagedPosts(int topicId,int pageNo,int pageSize); Page queryTopicByTitle(String title,int pageNo,int pageSize); Board getBoardById(int boardId); Topic getTopicByTopicId(int topicId); Post getPostByPostId(int postId); void addBoardManager(int boardId,String userName); void updateTopic(Topic topic); void updatePost(Post post); }### Answer:
@Test @DataSet("XiaoChun.DataSet.xls") public void addBoard() throws Exception { Board board = XlsDataSetBeanFactory.createBean(ForumServiceTest.class, "XiaoChun.DataSet.xls", "t_board", Board.class); forumService.addBoard(board); Board boardDb = forumService.getBoardById(board.getBoardId()); assertEquals(boardDb.getBoardName(), equalTo("育儿")); }
|
### Question:
ForumService { public void removeTopic(int topicId) { Topic topic = topicDao.get(topicId); Board board = boardDao.get(topic.getBoardId()); board.setTopicNum(board.getTopicNum() - 1); User user = topic.getUser(); user.setCredit(user.getCredit() - 50); topicDao.remove(topic); postDao.deleteTopicPosts(topicId); } @Autowired void setTopicDao(TopicDao topicDao); @Autowired void setUserDao(UserDao userDao); @Autowired void setBoardDao(BoardDao boardDao); @Autowired void setPostDao(PostDao postDao); void addTopic(Topic topic); void removeTopic(int topicId); void addPost(Post post); void removePost(int postId); void addBoard(Board board); void removeBoard(int boardId); void makeDigestTopic(int topicId); List<Board> getAllBoards(); Page getPagedTopics(int boardId,int pageNo,int pageSize); Page getPagedPosts(int topicId,int pageNo,int pageSize); Page queryTopicByTitle(String title,int pageNo,int pageSize); Board getBoardById(int boardId); Topic getTopicByTopicId(int topicId); Post getPostByPostId(int postId); void addBoardManager(int boardId,String userName); void updateTopic(Topic topic); void updatePost(Post post); }### Answer:
@Test @DataSet("XiaoChun.DataSet.xls") public void removeTopic() { forumService.removeTopic(1); Topic topicDb = forumService.getTopicByTopicId(1); assertNull(topicDb); }
|
### Question:
ForumService { public void removePost(int postId){ Post post = postDao.get(postId); postDao.remove(post); Topic topic = topicDao.get(post.getTopic().getTopicId()); topic.setReplies(topic.getReplies() - 1); User user =post.getUser(); user.setCredit(user.getCredit() - 20); } @Autowired void setTopicDao(TopicDao topicDao); @Autowired void setUserDao(UserDao userDao); @Autowired void setBoardDao(BoardDao boardDao); @Autowired void setPostDao(PostDao postDao); void addTopic(Topic topic); void removeTopic(int topicId); void addPost(Post post); void removePost(int postId); void addBoard(Board board); void removeBoard(int boardId); void makeDigestTopic(int topicId); List<Board> getAllBoards(); Page getPagedTopics(int boardId,int pageNo,int pageSize); Page getPagedPosts(int topicId,int pageNo,int pageSize); Page queryTopicByTitle(String title,int pageNo,int pageSize); Board getBoardById(int boardId); Topic getTopicByTopicId(int topicId); Post getPostByPostId(int postId); void addBoardManager(int boardId,String userName); void updateTopic(Topic topic); void updatePost(Post post); }### Answer:
@Test @DataSet("XiaoChun.DataSet.xls") public void removePost() { forumService.removePost(1); Post postDb = forumService.getPostByPostId(1); User userDb = userService.getUserByUserName("tom"); Topic topicDb = forumService.getTopicByTopicId(1); assertNull(postDb); assertEquals(userDb.getCredit(), equalTo(80)); assertEquals(topicDb.getReplies(), equalTo(0)); }
|
### Question:
ForumService { public void makeDigestTopic(int topicId){ Topic topic = topicDao.get(topicId); topic.setDigest(Topic.DIGEST_TOPIC); User user = topic.getUser(); user.setCredit(user.getCredit() + 100); } @Autowired void setTopicDao(TopicDao topicDao); @Autowired void setUserDao(UserDao userDao); @Autowired void setBoardDao(BoardDao boardDao); @Autowired void setPostDao(PostDao postDao); void addTopic(Topic topic); void removeTopic(int topicId); void addPost(Post post); void removePost(int postId); void addBoard(Board board); void removeBoard(int boardId); void makeDigestTopic(int topicId); List<Board> getAllBoards(); Page getPagedTopics(int boardId,int pageNo,int pageSize); Page getPagedPosts(int topicId,int pageNo,int pageSize); Page queryTopicByTitle(String title,int pageNo,int pageSize); Board getBoardById(int boardId); Topic getTopicByTopicId(int topicId); Post getPostByPostId(int postId); void addBoardManager(int boardId,String userName); void updateTopic(Topic topic); void updatePost(Post post); }### Answer:
@Test @DataSet("XiaoChun.DataSet.xls") public void makeDigestTopic()throws Exception { forumService.makeDigestTopic(1); User userDb = userService.getUserByUserName("tom"); Topic topicDb = forumService.getTopicByTopicId(1); assertEquals(userDb.getCredit(), equalTo(200)); assertEquals(topicDb.getDigest(), equalTo(Topic.DIGEST_TOPIC)); }
|
### Question:
JsonPatchListener implements DifferenceListener { public List<Difference> getDifferences() { return differences; } @Override void diff(final Difference difference, final DifferenceContext differenceContext); List<Difference> getDifferences(); DifferenceContext getContext(); DiffModel getDiffModel(); @SuppressWarnings({"all", "unchecked"}) String getJsonPatch(); }### Answer:
@Test void shouldSeeEmptyDiffNodes() { Diff diff = Diff.create("{}", "{}", "", "", commonConfig()); diff.similar(); assertThat(listener.getDifferences()) .isEmpty(); }
|
### Question:
JsonPatchListener implements DifferenceListener { public DifferenceContext getContext() { return context; } @Override void diff(final Difference difference, final DifferenceContext differenceContext); List<Difference> getDifferences(); DifferenceContext getContext(); DiffModel getDiffModel(); @SuppressWarnings({"all", "unchecked"}) String getJsonPatch(); }### Answer:
@Test void shouldSeeActualSource() throws JsonProcessingException { Diff diff = Diff.create("{\"test\": \"1\"}", "{}", "", "", commonConfig()); diff.similar(); assertThat(new ObjectMapper().writeValueAsString(listener.getContext().getActualSource())).isEqualTo("{}"); }
@Test void shouldSeeExpectedSource() throws JsonProcessingException { Diff diff = Diff.create("{\"test\": \"1\"}", "{}", "", "", commonConfig()); diff.similar(); assertThat(new ObjectMapper().writeValueAsString(listener.getContext().getExpectedSource())).isEqualTo("{\"test\":\"1\"}"); }
|
### Question:
AllureCucumber4Jvm implements ConcurrentEventListener { private String getHistoryId(final TestCase testCase) { final String testCaseLocation = testCase.getUri() + ":" + testCase.getLine(); return md5(testCaseLocation); } @SuppressWarnings("unused") AllureCucumber4Jvm(); AllureCucumber4Jvm(final AllureLifecycle lifecycle); @Override void setEventPublisher(final EventPublisher publisher); }### Answer:
@AllureFeatures.History @Test void shouldPersistHistoryIdForScenarios() { final AllureResultsWriterStub writer = new AllureResultsWriterStub(); runFeature(writer, "features/simple.feature"); final List<TestResult> testResults = writer.getTestResults(); assertThat(testResults.get(0).getHistoryId()) .isEqualTo("2f9965e6cc23d5c5f9c5268a2ff6f921"); }
|
### Question:
AllureCucumber6Jvm implements ConcurrentEventListener { private String getHistoryId(final TestCase testCase) { final String testCaseLocation = testCase.getUri().toString() .substring(testCase.getUri().toString().lastIndexOf('/') + 1) + ":" + testCase.getLine(); return md5(testCaseLocation); } @SuppressWarnings("unused") AllureCucumber6Jvm(); AllureCucumber6Jvm(final AllureLifecycle lifecycle); @Override void setEventPublisher(final EventPublisher publisher); }### Answer:
@AllureFeatures.History @Test void shouldPersistHistoryIdForScenarios() { final AllureResultsWriterStub writer = new AllureResultsWriterStub(); runFeature(writer, "features/simple.feature"); final List<TestResult> testResults = writer.getTestResults(); assertThat(testResults.get(0).getHistoryId()) .isEqualTo("8eea9ed4458a49d418859d1398580671"); }
|
### Question:
FreemarkerAttachmentRenderer implements AttachmentRenderer<AttachmentData> { @Override public DefaultAttachmentContent render(final AttachmentData data) { try (Writer writer = new StringWriter()) { final Template template = configuration.getTemplate(templateName); template.process(Collections.singletonMap("data", data), writer); return new DefaultAttachmentContent(writer.toString(), "text/html", ".html"); } catch (Exception e) { throw new AttachmentRenderException("Could't render http attachment file", e); } } FreemarkerAttachmentRenderer(final String templateName); @Override DefaultAttachmentContent render(final AttachmentData data); }### Answer:
@AllureFeatures.Attachments @Test void shouldRenderRequestAttachment() { final HttpRequestAttachment data = randomHttpRequestAttachment(); final DefaultAttachmentContent content = new FreemarkerAttachmentRenderer("http-request.ftl") .render(data); assertThat(content) .hasFieldOrPropertyWithValue("contentType", "text/html") .hasFieldOrPropertyWithValue("fileExtension", ".html") .hasFieldOrProperty("content"); }
@AllureFeatures.Attachments @Test void shouldRenderResponseAttachment() { final HttpRequestAttachment data = randomHttpRequestAttachment(); final DefaultAttachmentContent content = new FreemarkerAttachmentRenderer("http-response.ftl") .render(data); assertThat(content) .hasFieldOrPropertyWithValue("contentType", "text/html") .hasFieldOrPropertyWithValue("fileExtension", ".html") .hasFieldOrProperty("content"); }
|
### Question:
DefaultAttachmentProcessor implements AttachmentProcessor<AttachmentData> { @Override public void addAttachment(final AttachmentData attachmentData, final AttachmentRenderer<AttachmentData> renderer) { final AttachmentContent content = renderer.render(attachmentData); lifecycle.addAttachment( attachmentData.getName(), content.getContentType(), content.getFileExtension(), content.getContent().getBytes(StandardCharsets.UTF_8) ); } DefaultAttachmentProcessor(); DefaultAttachmentProcessor(final AllureLifecycle lifecycle); @Override void addAttachment(final AttachmentData attachmentData,
final AttachmentRenderer<AttachmentData> renderer); }### Answer:
@SuppressWarnings("unchecked") @AllureFeatures.Attachments @Test void shouldProcessAttachments() { final HttpRequestAttachment attachment = randomHttpRequestAttachment(); final AllureLifecycle lifecycle = mock(AllureLifecycle.class); final AttachmentRenderer<AttachmentData> renderer = mock(AttachmentRenderer.class); final AttachmentContent content = randomAttachmentContent(); doReturn(content) .when(renderer) .render(attachment); new DefaultAttachmentProcessor(lifecycle) .addAttachment(attachment, renderer); verify(renderer, times(1)).render(attachment); verify(lifecycle, times(1)) .addAttachment( eq(attachment.getName()), eq(content.getContentType()), eq(content.getFileExtension()), eq(content.getContent().getBytes(StandardCharsets.UTF_8)) ); }
|
### Question:
FileSystemResultsWriter implements AllureResultsWriter { @Override public void write(final TestResult testResult) { final String testResultName = Objects.isNull(testResult.getUuid()) ? generateTestResultName() : generateTestResultName(testResult.getUuid()); createDirectories(outputDirectory); final Path file = outputDirectory.resolve(testResultName); try { mapper.writeValue(file.toFile(), testResult); } catch (IOException e) { throw new AllureResultsWriteException("Could not write Allure test result", e); } } FileSystemResultsWriter(final Path outputDirectory); @Override void write(final TestResult testResult); @Override void write(final TestResultContainer testResultContainer); @Override void write(final String source, final InputStream attachment); }### Answer:
@Test void shouldNotFailIfNoResultsDirectory(@TempDir final Path folder) { Path resolve = folder.resolve("some-directory"); FileSystemResultsWriter writer = new FileSystemResultsWriter(resolve); final TestResult testResult = current().nextObject(TestResult.class, "steps"); writer.write(testResult); }
|
### Question:
AllureCucumber5Jvm implements ConcurrentEventListener { private String getHistoryId(final TestCase testCase) { final String testCaseLocation = testCase.getUri().toString() .substring(testCase.getUri().toString().lastIndexOf('/') + 1) + ":" + testCase.getLine(); return md5(testCaseLocation); } @SuppressWarnings("unused") AllureCucumber5Jvm(); AllureCucumber5Jvm(final AllureLifecycle lifecycle); @Override void setEventPublisher(final EventPublisher publisher); }### Answer:
@AllureFeatures.History @Test void shouldPersistHistoryIdForScenarios() { final AllureResultsWriterStub writer = new AllureResultsWriterStub(); runFeature(writer, "features/simple.feature"); final List<TestResult> testResults = writer.getTestResults(); assertThat(testResults.get(0).getHistoryId()) .isEqualTo("8eea9ed4458a49d418859d1398580671"); }
|
### Question:
Utils { public static void p(Object... args) { if (!BuildConfig.DEBUG) return; p(TextUtils.join(", ", args)); } static void p(Object... args); static void p(String msg); static void p(String format, Object... args); static int runOneCmdByRoot(String cmd, boolean isWait); static int screenshot(); static boolean hasRoot(); static int runCmd(String cmd, boolean isRoot, boolean isWait); static String is2String(InputStream is); }### Answer:
@Test public void testP() throws Exception { p("msg"); p("msg", "arg0"); p(1, "arg0"); }
@Test public void testEnv() { p(System.getenv()); }
|
### Question:
MulticastResult implements Serializable { public List<Result> getResults() { return results; } private MulticastResult(Builder builder); long getMulticastId(); int getSuccess(); int getTotal(); int getFailure(); int getCanonicalIds(); List<Result> getResults(); List<Long> getRetryMulticastIds(); @Override String toString(); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testResultsIsImmutable() { MulticastResult result = new MulticastResult.Builder(1, 2, 3, 4).build(); result.getResults().clear(); }
|
### Question:
MulticastResult implements Serializable { public List<Long> getRetryMulticastIds() { return retryMulticastIds; } private MulticastResult(Builder builder); long getMulticastId(); int getSuccess(); int getTotal(); int getFailure(); int getCanonicalIds(); List<Result> getResults(); List<Long> getRetryMulticastIds(); @Override String toString(); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testRetryMulticastIdsIsImmutable() { MulticastResult result = new MulticastResult.Builder(1, 2, 3, 4).build(); result.getRetryMulticastIds().clear(); }
|
### Question:
Sender { protected static final Map<String, String> newKeyValues(String key, String value) { Map<String, String> keyValues = new HashMap<String, String>(1); keyValues.put(nonNull(key), nonNull(value)); return keyValues; } Sender(String key); Result send(Message message, String registrationId, int retries); Result sendNoRetry(Message message, String registrationId); MulticastResult send(Message message, List<String> regIds, int retries); MulticastResult sendNoRetry(Message message,
List<String> registrationIds); }### Answer:
@Test public void testNewKeyValues() { Map<String, String> x = Sender.newKeyValues("key", "value"); assertEquals(1, x.size()); assertEquals("value", x.get("key")); }
@Test(expected = IllegalArgumentException.class) public void testNewKeyValues_nullKey() { Sender.newKeyValues(null, "value"); }
@Test(expected = IllegalArgumentException.class) public void testNewKeyValues_nullValue() { Sender.newKeyValues("key", null); }
|
### Question:
Sender { protected static StringBuilder newBody(String name, String value) { return new StringBuilder(nonNull(name)).append('=').append(nonNull(value)); } Sender(String key); Result send(Message message, String registrationId, int retries); Result sendNoRetry(Message message, String registrationId); MulticastResult send(Message message, List<String> regIds, int retries); MulticastResult sendNoRetry(Message message,
List<String> registrationIds); }### Answer:
@Test public void testNewBody() { StringBuilder body = Sender.newBody("name", "value"); assertEquals("name=value", body.toString()); }
@Test(expected = IllegalArgumentException.class) public void testNewBody_nullKey() { Sender.newBody(null, "value"); }
@Test(expected = IllegalArgumentException.class) public void testNewBody_nullValue() { Sender.newBody("key", null); }
|
### Question:
Sender { protected static void addParameter(StringBuilder body, String name, String value) { nonNull(body).append('&') .append(nonNull(name)).append('=').append(nonNull(value)); } Sender(String key); Result send(Message message, String registrationId, int retries); Result sendNoRetry(Message message, String registrationId); MulticastResult send(Message message, List<String> regIds, int retries); MulticastResult sendNoRetry(Message message,
List<String> registrationIds); }### Answer:
@Test public void testAddParameter() { StringBuilder body = new StringBuilder("P=NP"); Sender.addParameter(body, "name", "value"); assertEquals("P=NP&name=value", body.toString()); }
@Test(expected = IllegalArgumentException.class) public void testAddParameter_nullBody() { Sender.addParameter(null, "key", "value"); }
@Test(expected = IllegalArgumentException.class) public void testAddParameter_nullKey() { StringBuilder body = new StringBuilder(); Sender.addParameter(body, null, "value"); }
@Test(expected = IllegalArgumentException.class) public void testAddParameter_nullValue() { StringBuilder body = new StringBuilder(); Sender.addParameter(body, "key", null); }
|
### Question:
Sender { protected static String getString(InputStream stream) throws IOException { if (stream == null) { return ""; } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder content = new StringBuilder(); String newLine; do { newLine = reader.readLine(); if (newLine != null) { content.append(newLine).append('\n'); } } while (newLine != null); if (content.length() > 0) { content.setLength(content.length() - 1); } return content.toString(); } Sender(String key); Result send(Message message, String registrationId, int retries); Result sendNoRetry(Message message, String registrationId); MulticastResult send(Message message, List<String> regIds, int retries); MulticastResult sendNoRetry(Message message,
List<String> registrationIds); }### Answer:
@Test public void testGetString_oneLine() throws Exception { String expected = "108"; InputStream stream = new ByteArrayInputStream(expected.getBytes()); String actual = Sender.getString(stream); assertEquals(expected, actual); }
@Test public void testGetString_stripsLastLine() throws Exception { InputStream stream = new ByteArrayInputStream("108\n".getBytes()); String stripped = Sender.getString(stream); assertEquals("108", stripped); }
@Test public void testGetString_multipleLines() throws Exception { String expected = "4\n8\n15\n\n16\n23\n42"; InputStream stream = new ByteArrayInputStream(expected.getBytes()); String actual = Sender.getString(stream); assertEquals(expected, actual); }
|
### Question:
Message implements Serializable { public Map<String, String> getData() { return data; } private Message(Builder builder); String getCollapseKey(); Boolean isDelayWhileIdle(); Integer getTimeToLive(); Boolean isDryRun(); String getRestrictedPackageName(); Map<String, String> getData(); @Override String toString(); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testPayloadDataIsImmutable() { Message message = new Message.Builder().build(); message.getData().clear(); }
|
### Question:
ArtifactSizeEnforcerRule implements EnforcerRule { protected String getPackaging(EnforcerRuleHelper helper) throws EnforcerRuleException { String packaging; try { packaging = (String) helper.evaluate(PROJECT_PACKAGING_PROP); } catch (ExpressionEvaluationException e) { throw new EnforcerRuleException(e.getMessage()); } switch (packaging) { case JAR: return JAR; case BUNDLE: return JAR; default: return packaging; } } @Override void execute(EnforcerRuleHelper helper); @Override boolean isCacheable(); @Override boolean isResultValid(EnforcerRule enforcerRule); @Override String getCacheId(); ArtifactSizeEnforcerRule setMaxArtifactSize(String maxArtifactSize); ArtifactSizeEnforcerRule setArtifactLocation(String artifactLocation); static final String PROJECT_PACKAGING_PROP; static final String PROJECT_ARTIFACT_ID_PROP; static final String PROJECT_VERSION_PROP; static final String PROJECT_BUILD_DIR_PROP; static final String DEFAULT_MAX_ARTIFACT_SIZE; static final String BYTES; static final String MEGA_BYTES; static final String KILO_BYTES; static final String JAR; static final String BUNDLE; static final List<String> SUPPORTED_PACKAGE_TYPES; static final String MAX_FILE_SIZE_EXCEEDED_MSG; static final String DEFAULT_ARTIFACT_INFO_MSG; static final String UNKNOWN_ARTIFACT_SIZE_UNIT_MSG; }### Answer:
@Test public void unknownPackaging() { ArtifactSizeEnforcerRule enforcer = new ArtifactSizeEnforcerRule(); defaultMockhelper.packaging("UnknownPackageType"); try { String packaging = enforcer.getPackaging(defaultMockhelper); assertTrue(!SUPPORTED_PACKAGE_TYPES.contains(packaging)); } catch (EnforcerRuleException e) { fail("ArtifactSizerEnforcerRule was unable to skip an unknown packing type."); } }
|
### Question:
ExpectingUnion extends ExpectingOrderBy<RT> { public ExpectingUnion<RT> union(ExpectingUnion<RT> next) { statement.addUnion(next.statement, UnionType.UNION); return this; } ExpectingUnion(SelectStatement<RT> statement); ExpectingUnion<RT> union(ExpectingUnion<RT> next); ExpectingUnion<RT> unionAll(ExpectingUnion<RT> next); }### Answer:
@Test void union() { Database database = testDatabase(new AnsiDialect()); database.select(TypedExpression.value(1), "one") .union(database.select(TypedExpression.literal(2), "two")) .unionAll(database.select(TypedExpression.value(3), "three")) .orderBy(1) .list(transaction); verify(transaction).query(sql.capture(), args.capture(), rowMapper.capture()); assertThat(sql.getValue(), is("select ? as one from DUAL union select 2 as two from DUAL union all select ? as three from DUAL order by 1 asc")); assertThat(args.getValue(), is(toArray(1, 3))); }
|
### Question:
OptionalUtil extends UtilityClass { public static <T> Optional<T> ofOnly(Iterable<T> iterable) { if (iterable == null) { return Optional.empty(); } return Optional.ofNullable(Iterables.getOnlyElement(iterable, null)); } static Optional<T> ofBlankable(T s); static Optional<T> ofOnly(Iterable<T> iterable); static OptionalWrapper<T> with(Optional<T> optional); static Optional<T> or(Optional<T> optional, Optional<T> other); static Optional<T> orGet(Optional<T> optional, Supplier<? extends Optional<? extends T>> supplier); static Optional<U> as(Class<U> targetClass, Optional<T> source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, Optional<T> source); static Optional<U> as(Class<U> targetClass, T source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, T source); }### Answer:
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"null", "empty"}) @TestCase({"", "empty"}) @TestCase({"Some Value", "Some Value"}) void ofOnly(List<String> input, Optional<String> expected) { Optional<String> result = OptionalUtil.ofOnly(input); assertThat(result, is(expected)); }
@Test void ofOnlyWithMultipleThrows() { calling(() -> OptionalUtil.ofOnly(ImmutableList.of("A", "B"))) .shouldThrow(IllegalArgumentException.class) .withMessage("expected one element but was: <A, B>"); }
|
### Question:
OptionalUtil extends UtilityClass { public static <T> OptionalWrapper<T> with(Optional<T> optional) { return new OptionalWrapper<>(optional); } static Optional<T> ofBlankable(T s); static Optional<T> ofOnly(Iterable<T> iterable); static OptionalWrapper<T> with(Optional<T> optional); static Optional<T> or(Optional<T> optional, Optional<T> other); static Optional<T> orGet(Optional<T> optional, Supplier<? extends Optional<? extends T>> supplier); static Optional<U> as(Class<U> targetClass, Optional<T> source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, Optional<T> source); static Optional<U> as(Class<U> targetClass, T source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, T source); }### Answer:
@Test void withEmpty() { OptionalUtil.with(Optional.<String>empty()) .ifPresent(consumer) .otherwise(runnable); verify(consumer, never()).accept(any()); verify(runnable, times(1)).run(); }
@Test void withValue() { String value = RandomStringUtils.randomAscii(10); OptionalUtil.with(Optional.of(value)) .ifPresent(consumer) .otherwise(runnable); verify(consumer, times(1)).accept(value); verify(runnable, never()).run(); }
|
### Question:
OptionalUtil extends UtilityClass { public static <T> Optional<T> or(Optional<T> optional, Optional<T> other) { return optional.isPresent() ? optional : other; } static Optional<T> ofBlankable(T s); static Optional<T> ofOnly(Iterable<T> iterable); static OptionalWrapper<T> with(Optional<T> optional); static Optional<T> or(Optional<T> optional, Optional<T> other); static Optional<T> orGet(Optional<T> optional, Supplier<? extends Optional<? extends T>> supplier); static Optional<U> as(Class<U> targetClass, Optional<T> source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, Optional<T> source); static Optional<U> as(Class<U> targetClass, T source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, T source); }### Answer:
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"empty", "empty", "empty"}) @TestCase({"1", "empty", "1"}) @TestCase({"empty", "2", "2"}) @TestCase({"1", "2", "1"}) void or(Optional<Integer> a, Optional<Integer> b, Optional<Integer> expected) { Optional<Integer> result = OptionalUtil.or(a, b); assertThat(result, is(expected)); }
|
### Question:
OptionalUtil extends UtilityClass { public static <T> Optional<T> orGet(Optional<T> optional, Supplier<? extends Optional<? extends T>> supplier) { return optional.isPresent() ? optional : supplier.get().map(Function.identity()); } static Optional<T> ofBlankable(T s); static Optional<T> ofOnly(Iterable<T> iterable); static OptionalWrapper<T> with(Optional<T> optional); static Optional<T> or(Optional<T> optional, Optional<T> other); static Optional<T> orGet(Optional<T> optional, Supplier<? extends Optional<? extends T>> supplier); static Optional<U> as(Class<U> targetClass, Optional<T> source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, Optional<T> source); static Optional<U> as(Class<U> targetClass, T source); @SuppressWarnings("unchecked") static Optional<U> as(TypeToken<U> targetType, T source); }### Answer:
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"empty", "empty", "empty", "1"}) @TestCase({"123", "empty", "123", "0"}) @TestCase({"empty", "234", "234", "1"}) @TestCase({"123", "234", "123", "0"}) void orGet(Optional<Integer> a, Optional<Integer> b, Optional<Integer> expected, int expectedGets) { if (expectedGets > 0) { when(supplier.get()).thenReturn(b); } Optional<Integer> result = OptionalUtil.orGet(a, supplier); assertThat(result, is(expected)); verify(supplier, times(expectedGets)).get(); }
|
### Question:
SelectStatement { void keepLocks(LockLevel level) { keepLocks = Optional.of(level); } SelectStatement(Scope scope, TypeToken<RT> rowType, From from, RowMapper<RT> rowMapper, Projection projection); TypeToken<RT> rowType(); Stream<CommonTableExpression<?>> commonTableExpressions(); }### Answer:
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"SHARE", " for read only with rs use and keep SHARE locks"}) @TestCase({"UPDATE", " for read only with rs use and keep UPDATE locks"}) @TestCase({"EXCLUSIVE", " for read only with rs use and keep EXCLUSIVE locks"}) void keepLocks(LockLevel level, String lockSql) { SelectStatement<Integer> sut = new SelectStatement<>(createScope(), TypeToken.of(Integer.class), from, rowMapper, projection); sut.keepLocks(level); when(projection.sql(any())).thenReturn("col1"); when(from.sql(any())).thenReturn(" from tab1"); assertThat(sut.sql(), is("select col1 from tab1" + lockSql)); }
|
### Question:
Lazy { public Try<T> tryGet() { Try<T> result = value; if (result == null) { synchronized (lock) { result = value; if (result == null) { value = result = Try.trySupply(supplier); } } } return result; } <E extends Exception> Lazy(ThrowingSupplier<T,E> supplier); Try<T> tryGet(); T get(); Optional<T> optional(); Stream<T> stream(); boolean isKnown(); boolean isKnownSuccess(); boolean isKnownFailure(); Lazy<U> map(ThrowingFunction<? super T, ? extends U, E> function); Lazy<U> flatMap(ThrowingFunction<? super T, Lazy<U>, E> function); }### Answer:
@Test void tryGetSuccess() { Lazy<String> sut = new Lazy<>(() -> "Hello World"); Try<String> result = sut.tryGet(); assertThat(result, is(Try.success("Hello World"))); }
@Test void tryGetFailure() { Lazy<String> sut = new Lazy<>(() -> { throw new RuntimeException("Epic fail."); }); Try<String> result = sut.tryGet(); assertThat(result, is(Try.failure(new RuntimeException("Epic fail.")))); }
|
### Question:
Lazy { public T get() { return tryGet().orElseThrow(); } <E extends Exception> Lazy(ThrowingSupplier<T,E> supplier); Try<T> tryGet(); T get(); Optional<T> optional(); Stream<T> stream(); boolean isKnown(); boolean isKnownSuccess(); boolean isKnownFailure(); Lazy<U> map(ThrowingFunction<? super T, ? extends U, E> function); Lazy<U> flatMap(ThrowingFunction<? super T, Lazy<U>, E> function); }### Answer:
@Test void getSuccess() { Lazy<String> sut = new Lazy<>(() -> "Hello World"); String result = sut.get(); assertThat(result, is("Hello World")); }
@SuppressWarnings("unchecked") @Test void getOnceIfSuccessful() { ThrowingSupplier<String,RuntimeException> supplier = Mockito.mock(ThrowingSupplier.class); when(supplier.get()).thenReturn("Listen very carefully, I shall say this only once."); Lazy<String> sut = new Lazy<>(supplier); String result1 = sut.get(); String result2 = sut.get(); assertThat(result1, is("Listen very carefully, I shall say this only once.")); assertThat(result2, is("Listen very carefully, I shall say this only once.")); verify(supplier, times(1)).get(); }
@SuppressWarnings("unchecked") @Test void getOnlyOnceIfFailed() { ThrowingSupplier<String,RuntimeException> supplier = Mockito.mock(ThrowingSupplier.class); when(supplier.get()).thenThrow(new IllegalArgumentException("Bad argument.")); Lazy<String> sut = new Lazy<>(supplier); calling(sut::get) .shouldThrow(IllegalArgumentException.class) .withMessage("Bad argument."); calling(sut::get) .shouldThrow(IllegalArgumentException.class) .withMessage("Bad argument."); verify(supplier, times(1)).get(); }
|
### Question:
Lazy { public <U, E extends Exception> Lazy<U> map(ThrowingFunction<? super T, ? extends U, E> function) { return new Lazy<>(() -> tryGet().map(function).orElseThrow()); } <E extends Exception> Lazy(ThrowingSupplier<T,E> supplier); Try<T> tryGet(); T get(); Optional<T> optional(); Stream<T> stream(); boolean isKnown(); boolean isKnownSuccess(); boolean isKnownFailure(); Lazy<U> map(ThrowingFunction<? super T, ? extends U, E> function); Lazy<U> flatMap(ThrowingFunction<? super T, Lazy<U>, E> function); }### Answer:
@Test void mapSuccessFailure() { Lazy<String> sut = new Lazy<>(() -> "Hello"); Lazy<String> map = sut.map(s -> { throw new IllegalArgumentException("Too unfriendly."); }); calling(map::get) .shouldThrow(IllegalArgumentException.class) .withMessage("Too unfriendly."); }
@Test void mapFailure() { Lazy<String> sut = new Lazy<>(() -> { throw new UnsupportedOperationException("No greetings for you."); }); Lazy<String> map = sut.map(s -> s + " World!"); calling(map::get) .shouldThrow(UnsupportedOperationException.class) .withMessage("No greetings for you."); }
|
### Question:
StringUtil extends UtilityClass { public static String lowercaseFirst(String s) { if (StringUtils.isEmpty(s)) { return ""; } return s.substring(0, 1).toLowerCase() + s.substring(1); } static String lowercaseFirst(String s); static String uppercaseFirst(String s); static String camelToUpper(String camelName); static String hex(byte... bytes); static String octal(byte... bytes); static Function<T,String> prepend(String arg); static Function<T,String> append(String arg); }### Answer:
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"null", ""}) @TestCase({"", ""}) @TestCase({"a", "a"}) @TestCase({"B", "b"}) @TestCase({"abc", "abc"}) @TestCase({"ABC", "aBC"}) @TestCase({" DEF", " DEF"}) void lowercaseFirst(String input, String expected) { assertThat(StringUtil.lowercaseFirst(input), is(expected)); }
|
### Question:
StringUtil extends UtilityClass { public static String uppercaseFirst(String s) { if (StringUtils.isEmpty(s)) { return ""; } return s.substring(0, 1).toUpperCase() + s.substring(1); } static String lowercaseFirst(String s); static String uppercaseFirst(String s); static String camelToUpper(String camelName); static String hex(byte... bytes); static String octal(byte... bytes); static Function<T,String> prepend(String arg); static Function<T,String> append(String arg); }### Answer:
@ParameterizedTest @ArgumentsSource(TestCaseArgumentsProvider.class) @TestCase({"null", ""}) @TestCase({"", ""}) @TestCase({"a", "A"}) @TestCase({"B", "B"}) @TestCase({"abc", "Abc"}) @TestCase({" def", " def"}) void uppercaseFirst(String input, String expected) { assertThat(StringUtil.uppercaseFirst(input), is(expected)); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.