src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
NamingUtils { public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnon... | @Test public void shouldGetPartitionAddress() { assertThat(NamingUtils.getPartitionAddress("testAddress", 0)).isEqualTo("testAddress-0"); }
@Test(expected = NullPointerException.class) public void shouldNotAcceptNullAddressToGetPartitionAddress() { NamingUtils.getPartitionAddress(null, 0); } |
ArtemisProducerDestination implements ProducerDestination { @Override public String getNameForPartition(int i) { return getPartitionAddress(name, i); } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); } | @Test public void shouldGetNameForPartition() { String name = "test-name"; ArtemisProducerDestination destination = new ArtemisProducerDestination(name); assertThat(destination.getNameForPartition(0)).isEqualTo(getPartitionAddress(name, 0)); } |
ArtemisConsumerDestination implements ConsumerDestination { @Override public String getName() { return name; } ArtemisConsumerDestination(String name); @Override String getName(); @Override String toString(); } | @Test public void shouldGetName() { String name = "test-name"; ArtemisConsumerDestination destination = new ArtemisConsumerDestination(name); assertThat(destination.getName()).isEqualTo(name); } |
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClient... | @Test public void shouldCreateAddress() throws Exception { ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createAddress(address.toString(), artemisCommonProperties); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verif... |
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Ex... | @Test public void shouldCreateQueue() throws Exception { ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createQueue(address.toString(), queue.toString()); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verify(mockClien... |
ArtemisProvisioningProvider implements ProvisioningProvider<
ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> pro... | @Test public void shouldProvisionUnpartitionedProducer() { ProducerDestination destination = provider.provisionProducerDestination(address, mockProducerProperties); assertThat(destination).isInstanceOf(ArtemisProducerDestination.class); assertThat(destination.getName()).isEqualTo(address); verify(mockArtemisBrokerManag... |
ArtemisProvisioningProvider implements ProvisioningProvider<
ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerP... | @Test public void shouldProvisionUnpartitionedConsumer() { ConsumerDestination destination = provider.provisionConsumerDestination(address, null, mockConsumerProperties); assertThat(destination).isInstanceOf(ArtemisConsumerDestination.class); assertThat(destination.getName()).isEqualTo(address); verify(mockArtemisBroke... |
ListenerContainerFactory { public AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName) { DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer(); listenerContainer.setConnectionFactory(connectionFactory); listenerContainer.setPubSubDomain(true); ... | @Test public void shouldGetListenerContainer() { ListenerContainerFactory factory = new ListenerContainerFactory(mockConnectionFactory); AbstractMessageListenerContainer container = factory.getListenerContainer("testTopic", "testSubscription"); assertThat(container.getConnectionFactory()).isEqualTo(mockConnectionFactor... |
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); st... | @Test public void shouldGetQueueName() { assertThat(NamingUtils.getQueueName("testAddress", "testGroup")).isEqualTo("testAddress-testGroup"); }
@Test(expected = NullPointerException.class) public void shouldNotAcceptNullAddressToGetQueueName() { NamingUtils.getQueueName(null, "testGroup"); }
@Test(expected = NullPointe... |
NamingUtils { public static String getAnonymousGroupName() { UUID uuid = UUID.randomUUID(); ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); buffer.putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); return "anonymous-" + Base64Utils.encodeToUrlSafeString(buffer.array()) .replaceAll("=", ... | @Test public void shouldGetAnonymousQueueName() { assertThat(NamingUtils.getAnonymousGroupName()).hasSize(32) .startsWith("anonymous-"); } |
ArtemisMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>,
ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProduc... | @Test public void shouldCreateProducerMessageHandler() { MessageHandler handler = binder.createProducerMessageHandler(null, null, null); assertThat(handler).isInstanceOf(JmsSendingMessageHandler.class); } |
ArtemisMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>,
ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProduc... | @Test public void shouldCreateRegularConsumerEndpoint() { given(mockConsumerProperties.getMaxAttempts()).willReturn(1); ArtemisConsumerDestination destination = new ArtemisConsumerDestination("test-destination"); MessageProducer producer = binder.createConsumerEndpoint(destination, "test-group", mockConsumerProperties)... |
ArtemisProducerDestination implements ProducerDestination { @Override public String getName() { return name; } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); } | @Test public void shouldGetName() { String name = "test-name"; ArtemisProducerDestination destination = new ArtemisProducerDestination(name); assertThat(destination.getName()).isEqualTo(name); } |
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.s... | @Test public void readLabelsFromFile1() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-gold1.txt")); }
@Test public void readLabelsFromFile2() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-gold2.txt")); }
@Test(expected = IllegalArgumentException.class) public void rea... |
Scorer { public static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions) throws IllegalArgumentException { if (gold == null) { throw new IllegalArgumentException("Parameter 'gold' is null"); } if (predictions == null) { throw new IllegalArgumentException("Parameter 'predictions' is nul... | @Test public void computeAccuracy() throws Exception { Map<String, Integer> gold = Scorer .readLabelsFromFile(getFileFromResources("test-gold1.txt")); Map<String, Integer> predictions1 = Scorer .readLabelsFromFile(getFileFromResources("test-predictions1.txt")); assertEquals(0.6, Scorer.computeAccuracy(gold, predictions... |
LookupEngine { public String fetchDOI(String input) { Matcher doiMatcher = DOIPattern.matcher(input); while (doiMatcher.find()) { if (doiMatcher.groupCount() == 1) { return doiMatcher.group(1); } } return null; } LookupEngine(); LookupEngine(StorageEnvFactory storageFactory); String retrieveByArticleMetadata(String ti... | @Test public void getDOI_inInput_shouldWork() { String input = "{\"reference-count\":176,\"publisher\":\"IOP Publishing\",\"issue\":\"4\",\"content-domain\":{\"domain\":[],\"crossmark-restriction\":false},\"short-container-title\":[\"Russ. Chem. Rev.\"],\"published-print\":{\"date-parts\":[[1998,4,30]]},\"DOI\":\"10.10... |
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParameters... | @Test public void getByQuery_DOIexists_WithPostvalidation_shouldReturnJSONFromTitleFirstAuthor() { final String myDOI = "myDOI"; final boolean postValidate = true; final String atitle = "atitle"; final String firstAuthor = "firstAuthor"; final String jsonOutput = "{\"DOI\":\"" + myDOI + "\",\"title\":[\"" + atitle + "1... |
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } @Override void onStartDocument(XMLStreamReader2 reader); @Override void onEndDocument(XMLStreamReader2 reader); @Override void onStartElement(XMLStreamReader2 reader); @Override void onEndElement(XM... | @Test public void testParsingPublication_shouldWork() throws Exception { InputStream inputStream = this.getClass().getResourceAsStream("/sample.grobid.xml"); XMLStreamReader2 reader = (XMLStreamReader2) inputFactory.createXMLStreamReader(inputStream); StaxUtils.traverse(reader, target); GrobidResponseStaxHandler.Grobid... |
IstexIdsReader { public IstexData fromJson(String inputLine) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); return mapper.readValue(inputLine, IstexData.class); } catch (JsonGene... | @Test public void test() throws Exception { IstexData metadata = target.fromJson("{\"corpusName\":\"bmj\",\"istexId\":\"052DFBD14E0015CA914E28A0A561675D36FFA2CC\",\"ark\":[\"ark:/67375/NVC-W015BZV5-Q\"],\"doi\":[\"10.1136/sti.53.1.56\"],\"pmid\":[\"557360\"],\"pii\":[\"123\"]}"); assertThat(metadata, is(not(nullValue()... |
IstexIdsReader { public void load(String input, Consumer<IstexData> closure) { try (Stream<String> stream = Files.lines(Paths.get(input))) { stream.forEach(line -> closure.accept(fromJson(line))); } catch (IOException e) { LOGGER.error("Some serious error when processing the input Istex ID file.", e); } } void load(St... | @Test public void test3() throws Exception { target.load( new GZIPInputStream(this.getClass().getResourceAsStream("/sample-istex-ids.json.gz")), unpaidWallMetadata -> System.out.println(unpaidWallMetadata.getDoi() )); } |
PmidReader { public PmidData fromCSV(String inputLine) { final String[] split = StringUtils.splitPreserveAllTokens(inputLine, ","); if (split.length > 0 && split.length <= 3) { return new PmidData(split[0], split[1], replaceAll(split[2], "\"", "")); } return null; } void load(String input, Consumer<PmidData> closure);... | @Test public void test() throws Exception { PmidData metadata = target.fromCSV("9999996,,\"https: assertThat(metadata, is(not(nullValue()))); assertThat(metadata.getDoi(), is ("10.1103/physrevb.44.3678")); assertThat(metadata.getPmid(), is ("9999996")); assertThat(metadata.getPmcid(), is ("")); } |
SupplyLocationBulkUploadController { public List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations) { return this.service.saveSupplyLocationsZipContains504(locations); } @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository); @Autowired SupplyLocationBulkUploadControll... | @Test public void whenListFiltered_returnSavedList() { List<SupplyLocation> locations = new ArrayList<>(); locations.add(generateSupplyLocations(4, 4, "504")); when(service.saveSupplyLocationsZipContains504(inputLocations)).thenReturn(locations); assertThat(controller.uploadFitleredLocations(inputLocations)).size().isE... |
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); } | @Test public void disallowsNullKeyAndNullValue() { assertFalse(generator.okToAdd(null, null)); }
@Test public void disallowsNullKey() { assertFalse(generator.okToAdd(null, new Object())); }
@Test public void disallowsNullValue() { assertFalse(generator.okToAdd(new Object(), null)); }
@Test public void allowsKeyAndValue... |
Items { @SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List... | @Test public void choosingFromEmptyCollection() { thrown.expect(IllegalArgumentException.class); Items.choose(emptyList(), random); }
@Test public void choosingFromSet() { Set<String> names = new LinkedHashSet<>(asList("alpha", "bravo", "charlie", "delta")); when(random.nextInt(names.size())).thenReturn(2); assertEqual... |
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold ... | @Test public void choosingWeightedFromEmptyCollection() { thrown.expect(AssertionError.class); thrown.expectMessage("sample = 0, range = 0"); Items.chooseWeighted(emptyList(), random); }
@Test public void singleWeightedItem() { when(random.nextInt(2)).thenReturn(1); assertEquals("a", Items.chooseWeighted(singletonList(... |
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, ho... | @Test public void rejectsNegativeRemovalCount() { thrown.expect(IllegalArgumentException.class); Lists.removeFrom(newArrayList("abc"), -1); }
@Test public void removalsOfZeroElementsFromAList() { List<Integer> target = newArrayList(1, 2, 3); assertEquals(singletonList(target), Lists.removeFrom(target, 0)); }
@Test publ... |
Lists { public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(rando... | @Test public void shrinksOfEmptyList() { assertEquals(emptyList(), Lists.shrinksOfOneItem(random, emptyList(), null)); }
@Test public void shrinksOfNonEmptyList() { List<List<Integer>> shrinks = Lists.shrinksOfOneItem( random, newArrayList(1, 2, 3), (r, i) -> { assumeThat(r, sameInstance(random)); return newArrayList(4... |
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaTyp... | @Test public void rejectsNonFunctionalInterface() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(Cloneable.class + " is not a functional interface"); makeLambda(Cloneable.class, new AnInt(), status); }
@Test public void invokingDefaultMethodOnFunctionalInterface() { System.out.println(System.getP... |
Pair { @Override public String toString() { return String.format("[%s = %s]", first, second); } Pair(F first, S second); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); final F first; final S second; } | @Test public void stringifying() { assertEquals("[1 = 2]", new Pair<>(1, 2).toString()); } |
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral(
BigInteger max,
BigInteger start); static Iterable<BigDecimal> halvingDecimal(
... | @Test public void halvingBigIntegers() { assertEquals( newArrayList( BigInteger.valueOf(5), BigInteger.valueOf(7), BigInteger.valueOf(8), BigInteger.valueOf(9)), newArrayList(Sequences.halvingIntegral(BigInteger.TEN, BigInteger.ZERO))); }
@Test public void halvingNegativeBigIntegers() { assertEquals( newArrayList( BigI... |
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral(
BigInteger max,
BigInteger start); static Iterable<BigDecimal> halvingDecimal(
... | @Test public void halvingBigDecimals() { assertEquals( newArrayList( BigDecimal.valueOf(5), BigDecimal.valueOf(8), BigDecimal.valueOf(9), BigDecimal.TEN), newArrayList(Sequences.halvingDecimal(BigDecimal.TEN, BigDecimal.ZERO))); }
@Test public void halvingNegativeBigDecimals() { assertEquals( newArrayList( BigDecimal.v... |
Sequences { public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); } private Sequences(); static Iterable<BigInteger> halvingIntegral(
BigInteger max,
BigInteger start); static Iterable<BigDecimal> halvingDecimal(
BigDecimal max,
BigDecimal ... | @Test public void halvingInts() { assertEquals( newArrayList(27, 13, 6, 3, 1), newArrayList(Sequences.halving(27))); }
@Test public void callingNextOutOfSequenceOnHalvingInts() { Iterator<Integer> i = Sequences.halving(0).iterator(); i.next(); thrown.expect(NoSuchElementException.class); i.next(); } |
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); @Override Enum<?> generate(
SourceOfRandomness random,
GenerationStatus status); @Override boolean canShrink(Object larger); } | @Test public void capabilityOfShrinkingNonEnum() { assertFalse(generator.canShrink(new Object())); }
@Test public void capabilityOfShrinkingEnumOfDesiredType() { assertTrue(generator.canShrink(ElementType.METHOD)); }
@Test public void capabilityOfShrinkingEnumOfOtherType() { assertFalse(generator.canShrink(RetentionPol... |
CompositeGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); } CompositeGenerator(List<Weighted<Generator<?>>> composed); @Override Object generate(SourceOfRandomness random, GenerationStatus status); @... | @Test public void capabilityOfShrinkingDependsOnComponents() { when(first.canShrink(9)).thenReturn(true); when(second.canShrink(9)).thenReturn(false); when(third.canShrink(9)).thenReturn(true); assertTrue(composite.canShrink(9)); }
@Test public void capabilityOfShrinkingFalseIfNoComponentsCanShrinkAValue() { when(first... |
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); void configure(Size size); void configure(Distinct distinct); @Override Object generate(
... | @Test public void capabilityOfShrinkingNonArray() { assertFalse(intArrayGenerator.canShrink(3)); }
@Test public void capabilityOfShrinkingArrayOfIdenticalComponentType() { assertTrue(intArrayGenerator.canShrink(new int[0])); }
@Test public void capabilityOfShrinkingArrayOfEquivalentWrapperComponentType() { assertFalse(... |
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (... | @Test public void leastMagnitudeUnbounded() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(null, null, 0)); }
@Test public void leastMagnitudeNegativeMinOnly() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(-3, null, 0)); }
@Test public void leastMagnitudePositiveMinOnly() { assertEquals(I... |
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); } | @Test public void negativeProbability() { thrown.expect(IllegalArgumentException.class); distro.sample(-ulp(0), random); }
@Test public void zeroProbability() { thrown.expect(IllegalArgumentException.class); distro.sample(0, random); }
@Test public void greaterThanOneProbability() { thrown.expect(IllegalArgumentExcepti... |
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } int sampleWithMean(double mean, SourceOfRandomness random); } | @Test public void negativeMeanProbability() { thrown.expect(IllegalArgumentException.class); distro.probabilityOfMean(-ulp(0)); }
@Test public void zeroMeanProbability() { thrown.expect(IllegalArgumentException.class); distro.probabilityOfMean(0); }
@Test public void nonZeroMeanProbability() { assertEquals(1 / 6D, dist... |
GeometricDistribution { public int sampleWithMean(double mean, SourceOfRandomness random) { return sample(probabilityOfMean(mean), random); } int sampleWithMean(double mean, SourceOfRandomness random); } | @Test public void sampleWithMean() { when(random.nextDouble()).thenReturn(0.76); assertEquals(8, distro.sampleWithMean(6, random)); } |
Reflection { public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructo... | @Test public void findingConstructorQuietly() { Constructor<Integer> ctor = findConstructor(Integer.class, int.class); assertEquals(int.class, ctor.getParameterTypes()[0]); }
@Test public void findingConstructorQuietlyWhenNoSuchConstructor() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodE... |
Reflection { public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Cl... | @Test public void findingDeclaredConstructorQuietly() { Constructor<Integer> ctor = findDeclaredConstructor(Integer.class, int.class); assertEquals(int.class, ctor.getParameterTypes()[0]); }
@Test public void findingDeclaredConstructorQuietlyWhenNoSuchConstructor() { thrown.expect(ReflectionException.class); thrown.exp... |
CodePoints { public static CodePoints forCharset(Charset c) { if (ENCODABLES.containsKey(c)) return ENCODABLES.get(c); CodePoints points = load(c); ENCODABLES.put(c, points); return points; } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); } | @Test public void versusCharsetThatDoesNotSupportEncoding() { Charset noEncoding; try { noEncoding = Charset.forName("ISO-2022-CN"); } catch (UnsupportedCharsetException testNotValid) { return; } thrown.expect(IllegalArgumentException.class); CodePoints.forCharset(noEncoding); } |
Reflection { @SuppressWarnings("unchecked") public static <T> Constructor<T> singleAccessibleConstructor( Class<T> type) { Constructor<?>[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new ReflectionException( type + " needs a single accessible constructor"); } return (Constructor<T>) co... | @Test public void findingSingleAccessibleConstructorSuccessfully() { Constructor<Object> ctor = singleAccessibleConstructor(Object.class); assertEquals(0, ctor.getParameterTypes().length); }
@Test public void rejectsFindingSingleAccessibleConstructorOnNonConformingClass() { thrown.expect(ReflectionException.class); thr... |
Reflection { public static <T> T instantiate(Class<T> clazz) { try { return clazz.newInstance(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor(
Class<T> type,
Class<?>... parameterTypes)... | @Test public void invokingZeroArgConstructorQuietlyWrapsInstantiationException() { thrown.expect(ReflectionException.class); thrown.expectMessage(InstantiationException.class.getName()); instantiate(ZeroArgInstantiationProblematic.class); }
@Test public void invokingZeroArgConstructorQuietlyWrapsIllegalAccessException(... |
Reflection { public static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes) { try { return target.getMethod(methodName, argTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstruct... | @Test public void findingNonExistentMethodQuietlyWrapsNoSuchMethodException() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); findMethod(getClass(), "foo"); } |
CodePoints { public int at(int index) { if (index < 0) throw new IndexOutOfBoundsException("illegal negative index: " + index); int min = 0; int max = ranges.size() - 1; while (min <= max) { int midpoint = min + ((max - min) / 2); CodePointRange current = ranges.get(midpoint); if (index >= current.previousCount && inde... | @Test public void lowIndex() { thrown.expect(IndexOutOfBoundsException.class); new CodePoints().at(-1); }
@Test public void highIndex() { thrown.expect(IndexOutOfBoundsException.class); new CodePoints().at(0); } |
Reflection { public static Object invoke(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor(
Class<T> type,
... | @Test public void invokingMethodQuietlyWrapsIllegalAccessException() throws Exception { Method method = ZeroArgIllegalAccessProblematic.class.getDeclaredMethod("foo"); thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); invoke(method, new ZeroArgIllegalAccessProblemat... |
Reflection { public static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute) { try { return annotationType.getMethod(attribute).getDefaultValue(); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Const... | @Test public void findingDefaultValueOfAnnotationAttribute() throws Exception { assertEquals("baz", defaultValueOf(Foo.class, "bar")); }
@Test public void missingAnnotationAttribute() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); defaultValueOf... |
Reflection { public static Method singleAbstractMethodOf(Class<?> rawClass) { if (!rawClass.isInterface()) return null; int abstractCount = 0; Method singleAbstractMethod = null; for (Method each : rawClass.getMethods()) { if (isAbstract(each.getModifiers()) && !overridesJavaLangObjectMethod(each)) { singleAbstractMeth... | @Test public void aClassIsNotASingleAbstractMethodType() { assertNull(singleAbstractMethodOf(String.class)); }
@Test public void anInterfaceWithNoMethodsIsNotASingleAbstractMethodType() { assertNull(singleAbstractMethodOf(Serializable.class)); }
@Test public void anInterfaceWithASingleAbstractMethodIsASingleAbstractMet... |
Reflection { public static boolean isMarkerInterface(Class<?> clazz) { if (!clazz.isInterface()) return false; return Arrays.stream(clazz.getMethods()) .filter(m -> !m.isDefault()) .noneMatch(m -> !overridesJavaLangObjectMethod(m)); } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<... | @Test public void aClassIsNotAMarkerInterface() { assertFalse(isMarkerInterface(Object.class)); }
@Test public void anInterfaceWithAMethodIsNotAMarkerInterface() { assertFalse(isMarkerInterface(NotAMarker.class)); }
@Test public void anInterfaceWithNoMethodsButSuperMethodsIsNotAMarkerInterface() { assertFalse(isMarkerI... |
CodePoints { public int size() { if (ranges.isEmpty()) return 0; CodePointRange last = ranges.get(ranges.size() - 1); return last.previousCount + last.size(); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); } | @Test public void sizeOfEmpty() { assertEquals(0, new CodePoints().size()); } |
Reflection { public static void setField( Field field, Object target, Object value, boolean suppressProtection) { doPrivileged((PrivilegedAction<Void>) () -> { field.setAccessible(suppressProtection); return null; }); try { field.set(target, value); } catch (Exception ex) { throw reflectionException(ex); } } private R... | @Test public void settingFieldWithoutBypassingProtection() throws Exception { WithAccessibleField target = new WithAccessibleField(); setField(target.getClass().getField("i"), target, 2, false); assertEquals(2, target.i); }
@Test public void settingInaccessibleFieldBypassingProtection() throws Exception { WithInaccessi... |
Reflection { public static List<Field> allDeclaredFieldsOf(Class<?> type) { List<Field> allFields = new ArrayList<>(); for (Class<?> c = type; c != null; c = c.getSuperclass()) Collections.addAll(allFields, c.getDeclaredFields()); List<Field> results = allFields.stream() .filter(f -> !f.isSynthetic()) .collect(toList()... | @Test public void findingAllDeclaredFieldsOnAClass() throws Exception { List<Field> fields = allDeclaredFieldsOf(Child.class); assertEquals(2, fields.size()); assertThat(fields, hasItem(Child.class.getDeclaredField("s"))); assertThat(fields, hasItem(Parent.class.getDeclaredField("i"))); }
@Test public void findingAllDe... |
VoidGenerator extends Generator<Void> { @Override public Void generate(SourceOfRandomness random, GenerationStatus status) { return null; } @SuppressWarnings("unchecked") VoidGenerator(); @Override Void generate(SourceOfRandomness random, GenerationStatus status); @Override boolean canRegisterAsType(Class<?> type); } | @Test public void canOnlyGenerateNull() { VoidGenerator generator = new VoidGenerator(); Void value = generator.generate(null, null); assertNull(value); } |
Reflection { public static Field findField(Class<?> type, String fieldName) { try { return type.getDeclaredField(fieldName); } catch (NoSuchFieldException ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor(
Class<T> ty... | @Test public void findingField() { Field i = findField(Parent.class, "i"); assertEquals(int.class, i.getType()); }
@Test public void findingNonExistentField() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchFieldException.class.getName()); findField(Parent.class, "missing"); } |
Ranges { static long findNextPowerOfTwoLong(long positiveLong) { return isPowerOfTwoLong(positiveLong) ? positiveLong : ((long) 1) << (64 - Long.numberOfLeadingZeros(positiveLong)); } private Ranges(); static int checkRange(
Type type,
T min,
T max); static BigInteger choose(
SourceOfRa... | @Test public void checkFindNextPowerOfTwoLong() { assertEquals(1, findNextPowerOfTwoLong(1)); assertEquals(2, findNextPowerOfTwoLong(2)); assertEquals(4, findNextPowerOfTwoLong(3)); assertEquals(4, findNextPowerOfTwoLong(4)); assertEquals(8, findNextPowerOfTwoLong(5)); assertEquals((long) 1 << 61, findNextPowerOfTwoLon... |
Ranges { public static BigInteger choose( SourceOfRandomness random, BigInteger min, BigInteger max) { BigInteger range = max.subtract(min).add(BigInteger.ONE); BigInteger generated; do { generated = random.nextBigInteger(range.bitLength()); } while (generated.compareTo(range) >= 0); return generated.add(min); } privat... | @Test public void weakSanityCheckForDistributionOfChooseLongs() { boolean[] hits = new boolean[5]; SourceOfRandomness random = new SourceOfRandomness(new Random(0)); for (int i = 0; i < 100; i++) { hits[(int) Ranges.choose(random, 0, (long) hits.length - 1)] = true; } for (boolean hit : hits) { assertTrue(hit); } } |
MappingsResolver { public static List<String> getRequestMappings(Method method, Class<?> controller) { return getJoinedMappings(method, controller, PathExtractor.of(RequestMapping.class, RequestMapping::path)); } static List<String> getRequestMappings(Method method, Class<?> controller); static List<String> getMessage... | @Test public void getRequestMappings_noClassAnnotation() throws NoSuchMethodException { Class<?> ctrl = StandardController.class; Method none = ctrl.getDeclaredMethod("none"); Method slash = ctrl.getDeclaredMethod("slash"); Method slashPath = ctrl.getDeclaredMethod("slashPath"); Method longPath = ctrl.getDeclaredMethod... |
FieldPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { Class<?> clazz = extractClass(type); return getAllFields(clazz).stream() .filter(FieldPropertyScanner::isRelevantWhenSerialized) .map(FieldPropertyScanner::toProperty) .collect(toList()); } @Override List<Prope... | @Test public void getFieldTypes_primitive() { List<Property> props = scanner.getProperties(int.class); assertTrue(props.isEmpty()); }
@Test public void getFieldTypes_excludesTransient() throws NoSuchFieldException { Set<Property> props = new HashSet<>(); props.add(createFieldProperty("stringField", String.class, Custom... |
RecursivePropertyTypeScanner implements TypeScanner { @Override public Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes) { Set<Class<?>> allTypes = new HashSet<>(); rootTypes.forEach(type -> exploreType(type, allTypes)); return allTypes; } RecursivePropertyTypeScanner(PropertyScanner scanner); Pre... | @Test public void findTypes_simpleString() { Set<Type> rootTypes = Collections.singleton(String.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), String.class); }
@Test public void findTypes_simpleCharacter() { Set<Type> rootTypes = Collections.singleton(Character.class); assertSetEquals(explorer.findTyp... |
ConcreteSubtypesMapper implements Function<Class<?>, Set<Class<?>>> { @Override public Set<Class<?>> apply(Class<?> type) { if (isAbstract(type)) { return getImplementationsOf(type); } return Collections.singleton(type); } ConcreteSubtypesMapper(Reflections reflections); @Override Set<Class<?>> apply(Class<?> type); } | @Test public void apply_concreteClass() { assertEquals(mapper.apply(SimpleAImpl.class), SimpleAImpl.class); assertEquals(mapper.apply(ConcreteAImpl.class), ConcreteAImpl.class); assertEquals(mapper.apply(BImpl.class), BImpl.class); }
@Test public void apply_abstractClass() { assertEquals(mapper.apply(AbstractA.class), ... |
Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } static Object defaultValueFor(@Nullable Class<?> type); } | @Test public void defaultValueFor_primitives() { assertEquals(0, Defaults.defaultValueFor(byte.class)); assertEquals(0, Defaults.defaultValueFor(short.class)); assertEquals(0, Defaults.defaultValueFor(int.class)); assertEquals(0L, Defaults.defaultValueFor(long.class)); assertEquals(0f, Defaults.defaultValueFor(float.cl... |
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz, @NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider) { TypeDoc doc = new TypeDoc(clazz); doc.setName(clazz.getSimpleName()); doc.setDescripti... | @Test public void buildTypeDocBase() { Optional<TypeDoc> doc = reader.buildTypeDocBase(Person.class, typeReferenceProvider, c -> null); assertTrue(doc.isPresent()); TypeDoc typeDoc = doc.get(); assertEquals("Person", typeDoc.getName()); assertEquals("Represents a person.", typeDoc.getDescription()); } |
JavadocTypeDocReader implements TypeDocReader { @NotNull @Override public Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc, TypeReferenceProvider typeReferenceProvider) { PropertyDoc doc = new PropertyDoc(); doc.setName(property.getName()); doc.setDescription(getPropertyDescription(property))... | @Test public void buildPropertyDoc() throws NoSuchMethodException, NoSuchFieldException { Field nameField = Person.class.getDeclaredField("name"); Field ageField = Person.class.getDeclaredField("age"); Field phoneField = Person.class.getDeclaredField("phone"); Method getName = Person.class.getDeclaredMethod("getName");... |
JacksonPropertyScanner implements PropertyScanner { @Override public List<Property> getProperties(Type type) { return getJacksonProperties(type).stream() .filter(JacksonPropertyScanner::isReadable) .map(this::convertProp) .collect(toList()); } JacksonPropertyScanner(ObjectMapper mapper); @Override List<Property> getPro... | @Test public void getProperties_primitive() { assertTrue(scanner.getProperties(int.class).isEmpty()); } |
RestUserDetailsService implements UserDetailsManager { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return restTemplate.getForObject("/{0}", User.class, username); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app... | @Test public void testLoadUserByUsername() { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withHalJsonResponse("/user_jbloggs_GET.txt")); UserDetails userDetails = service.loadUserByUsername(USERNAME); assertNotNull(userDetails); } |
SpannersService { public void create(Spanner spanner) { restTemplate.postForObject("/", spanner, Spanner.class); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPer... | @Test public void testCreate() throws Exception { server.expect(requestTo("/")).andExpect(method(POST)) .andRespond(withStatus(HttpStatus.CREATED)); Spanner newSpanner = aSpanner().withId(null).build(); service.create(newSpanner); server.verify(); } |
SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void update(Spanner spanner) { restTemplate.put("/{0}", spanner, spanner.getId()); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Sp... | @Test public void testUpdate() throws Exception { server.expect(requestTo("/1")).andExpect(method(PUT)) .andRespond(withStatus(HttpStatus.OK)); Spanner update = aSpanner().withId(1L).build(); service.update(update); server.verify(); } |
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage() { SpannerForm newSpanner = new SpannerForm(); return new ModelAndView(VIEW_ADD_SPANNER, MODEL_SPANNER, newSpanner); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAnd... | @Test public void testPageDisplay() { ModelAndView response = controller.displayPage(); assertNotNull("no response", response); assertEquals("view", VIEW_ADD_SPANNER, response.getViewName()); } |
AddSpannerController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal) { if (validationResult.hasErrors()) { return new ModelAndView(VIEW_VALIDATION_FAIL);... | @Test public void testAddSpanner() { SpannerForm formData = new SpannerForm(); formData.setName("Keeley"); formData.setSize(12); Principal currentUser = new TestingAuthenticationToken("user", "pass"); BindingResult noErrors = new BeanPropertyBindingResult(formData, MODEL_SPANNER); ModelAndView response = controller.add... |
DetailSpannerController { @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) public ModelAndView displayDetail(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } return new ModelAndVi... | @Test public void testDisplayPage() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER); ModelAndView response = controller.displayDetail(SPANNER_ID); assertNotNull("no response", response); assertEquals(VIEW_DETAIL_SPANNER, response.getViewName()); Spanner spannerInModel = (Spanner)respons... |
HomeController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String index() { return VIEW_NOT_SIGNED_IN; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String index(); static final String CONTROLLER_URL; static final String VIEW_NOT_SIGNED_IN; } | @Test public void testHomePage() { String response = controller.index(); assertEquals("view name", VIEW_NOT_SIGNED_IN, response); } |
SignupController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) public String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors) { if (errors.hasErrors()) { log.warn("Oh no! Signup failed as there are validation errors."); return null; } String hashedPassword = passwordEncoder.e... | @Test public void testSuccessForward() { SignupForm form = populateForm(NAME, PASSWORD); Errors noErrors = new DirectFieldBindingResult(form, "form"); String response = controller.signup(form, noErrors); assertEquals(SignupController.VIEW_SUCCESS, response); }
@Test public void testAccountCreation() { SignupForm form =... |
RestUserDetailsService implements UserDetailsManager { @Override public void createUser(UserDetails userDetails) { restTemplate.postForLocation("/", userDetails); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDet... | @Test public void testCreateUser() throws Exception { server.expect(requestTo("/")).andExpect(method(POST)) .andRespond(withStatus(HttpStatus.CREATED)); UserDetails user = new User(USERNAME, PASSWORD, ENABLED); service.createUser(user); server.verify(); } |
DisplaySpannersController { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public String displaySpanners(ModelMap model) { Collection<Spanner> spanners = spannersService.findAll(); String greeting = timeOfDayGreeting(); model.addAttribute(MODEL_ATTRIBUTE_SPANNERS, spanners); model.addAttribute(MODE... | @Test public void testDisplaySpanners() { when(spannersService.findAll()).thenReturn(SPANNERS); ModelMap model = new ModelMap(); String view = controller.displaySpanners(model); assertEquals("view name", VIEW_DISPLAY_SPANNERS, view); @SuppressWarnings("unchecked") List<Spanner> spannersInModel = (List<Spanner>)model.ge... |
DisplaySpannersController { @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) public String deleteSpanner(@RequestParam Long id, ModelMap model) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundException(id); } spannersS... | @Test public void testDeleteSpanner() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER); ModelMap model = new ModelMap(); String view = controller.deleteSpanner(SPANNER_ID, model); verify(spannersService).delete(SPANNER); assertEquals("view name", VIEW_DISPLAY_SPANNERS, view); }
@Test pub... |
EditSpannerController implements ApplicationEventPublisherAware { @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) public ModelAndView displayPage(@RequestParam Long id) throws SpannerNotFoundException { Spanner spanner = spannersService.findOne(id); if (spanner == null) { throw new SpannerNotFoundEx... | @Test public void testDisplayPage() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(SPANNER); ModelAndView response = controller.displayPage(SPANNER_ID); assertNotNull("no response", response); assertEquals("view", VIEW_EDIT_SPANNER, response.getViewName()); SpannerForm spannerFormData = (Spanne... |
RestUserDetailsService implements UserDetailsManager { @Override public void updateUser(UserDetails userDetails) { restTemplate.put("/{0}", userDetails, userDetails.getUsername()); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri);... | @Test public void testUpdateUser() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(PUT)) .andRespond(withStatus(HttpStatus.OK)); UserDetails user = new User(USERNAME, PASSWORD, ENABLED); service.updateUser(user); server.verify(); } |
RestUserDetailsService implements UserDetailsManager { @Override public void deleteUser(String username) { restTemplate.delete("/{0}", username); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUs... | @Test public void testDeleteUser() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(DELETE)) .andRespond(withStatus(HttpStatus.OK)); service.deleteUser(USERNAME); server.verify(); } |
RestUserDetailsService implements UserDetailsManager { @Override public boolean userExists(String username) { try { ResponseEntity<User> responseEntity = restTemplate.getForEntity("/{0}", User.class, username); return HttpStatus.OK.equals(responseEntity.getStatusCode()); } catch (HttpClientErrorException e) { return fa... | @Test public void testUserExists() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withHalJsonResponse("/user_jbloggs_GET.txt")); boolean userExists = service.userExists(USERNAME); assertTrue(userExists); }
@Test public void testUserNotExists() throws Exception { server.ex... |
RestUserDetailsService implements UserDetailsManager { @Override public void changePassword(String username, String password) { User user = new User(); user.setUsername(username); user.setPassword(password); HttpEntity<User> requestEntity = new HttpEntity<>(user); restTemplate.exchange("/{0}", HttpMethod.PATCH, request... | @Test public void changePassword() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(PATCH)) .andRespond(withStatus(HttpStatus.OK)); service.changePassword(USERNAME, PASSWORD); server.verify(); } |
SpannersService { public Collection<Spanner> findAll() { ResponseEntity<PagedResources<Spanner>> response = restTemplate.exchange("/", HttpMethod.GET, null, new ParameterizedTypeReference<PagedResources<Spanner>>(){}); PagedResources<Spanner> pages = response.getBody(); return pages.getContent(); } SpannersService(Rest... | @Test public void testFindAll() throws Exception { server.expect(requestTo("/")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spannersGET.txt")); Collection<Spanner> spanners = service.findAll(); assertThat(spanners, hasSize(2)); } |
SpannersService { public Spanner findOne(Long id) { return restTemplate.getForObject("/{0}", Spanner.class, id); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPer... | @Test public void testFindOne() throws Exception { server.expect(requestTo("/1")).andExpect(method(GET)) .andRespond(withHalJsonResponse("/spanner1GET.txt")); Spanner spanner = service.findOne(1L); assertSpanner("Belinda", 10, "jones", spanner); } |
SpannersService { @PreAuthorize("hasPermission(#spanner, 'owner')") public void delete(Spanner spanner) { restTemplate.delete("/{0}", spanner.getId()); } SpannersService(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner ... | @Test public void testDelete() throws Exception { server.expect(requestTo("/1")).andExpect(method(DELETE)) .andRespond(withStatus(HttpStatus.NO_CONTENT)); Spanner susan = aSpanner().withId(1L).named("Susan").build(); service.delete(susan); server.verify(); } |
MongoDbController { @GetMapping("/mongo/findAll") public List<Book> findAll() { return mongoDbService.findAll(); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam String id); @GetMapping("/m... | @Test public void findAllTest() throws Exception{ MockUtils.mockGetTest("/mongo/findAll",mockMvc); } |
MongoDbController { @PostMapping("/mongo/update") public String update(@RequestBody Book book) { return mongoDbService.updateBook(book); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOne(@RequestParam Str... | @Test public void updateTest() throws Exception{ Book book = new Book(); book.setId("4"); book.setPrice(130); book.setName("VUE从入门到放弃"); book.setInfo("前端框架--更新"); Gson gson = new Gson(); String params = gson.toJson(book); MvcResult mvcResult = MockUtils.mockPostTest("/mongo/delOne",params,mockMvc); String result = mvcR... |
MongoDbController { @GetMapping("/mongo/findLikes") public List<Book> findByLikes(@RequestParam String search) { return mongoDbService.findByLikes(search); } @PostMapping("/mongo/save") String saveObj(@RequestBody Book book); @GetMapping("/mongo/findAll") List<Book> findAll(); @GetMapping("/mongo/findOne") Book findOn... | @Test public void findByLikesTest() throws Exception{ MockUtils.mockGetTest("/mongo/findLikes?search=从",mockMvc); } |
OptimizedBubbleSort { public <T> int sort(T[] array, Comparator<T> comparator, boolean optimized) { if (array == null) { return 0; } int counter = 0; boolean swapped = true; int lastSwap = array.length-1; while (swapped) { swapped = false; int limit = array.length - 1; if(optimized){ limit = lastSwap; } for (int i = 0;... | @Test public void testNull(){ int comparisons = sorter.sort(null, new StringComparator(), false); assertEquals(0, comparisons); }
@Test public void testAlreadySorted(){ String[] array = {"a", "b", "c", "d"}; int comparisons = sorter.sort(array, new StringComparator(), false); assertEquals(3, comparisons); assertEquals(... |
TriangleClassification { public static Classification classify(int a, int b, int c) { if(a <= 0 || b <= 0 || c <= 0){ return NOT_A_TRIANGLE; } if(a==b && b==c){ return EQUILATERAL; } int max = Math.max(a, Math.max(b, c)); if ((max == a && max - b - c >= 0) || (max == b && max - a - c >= 0) || (max == c && max - a - b >... | @Test public void testNegativeA(){ Classification res = TriangleClassification.classify(-1, 1, 1); assertEquals(NOT_A_TRIANGLE, res); }
@Test public void testNegativeB(){ Classification res = TriangleClassification.classify(1, -1, 1); assertEquals(NOT_A_TRIANGLE, res); }
@Test public void testNegativeC(){ Classificatio... |
MyRingArrayQueue implements MyQueue<T> { @Override public T peek() { if(isEmpty()){ throw new RuntimeException(); } return (T) data[head]; } MyRingArrayQueue(); MyRingArrayQueue(int capacity); @Override void enqueue(T value); @Override T dequeue(); @Override T peek(); @Override int size(); } | @Test public void testFailToPeekOnEmpty(){ assertThrows(RuntimeException.class, () -> queue.peek()); } |
CopyExample { public static String[] copyWrong(String[] input){ if(input == null){ return null; } String[] output = input; return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWrong(String[][] input); static String[][] copy(String[][] input); } | @Test public void testCopyArrayWrong(){ String[] foo = {"hello", "there", "!"}; String[] copy = CopyExample.copyWrong(foo); checkSameData(foo, copy); String WRONG = "WRONG"; copy[0] = WRONG; assertEquals(WRONG, foo[0]); }
@Test public void testCopyMatrixWrong(){ String[][] foo = new String[2][]; foo[0] = new String[]{"... |
CopyExample { public static String[] copy(String[] input){ if(input == null){ return null; } String[] output = new String[input.length]; for(int i=0; i<output.length; i++){ output[i] = input[i]; } return output; } static String[] copyWrong(String[] input); static String[] copy(String[] input); static String[][] copyWr... | @Test public void testCopyArray(){ String[] foo = {"hello", "there", "!"}; String[] copy = CopyExample.copy(foo); checkSameData(foo, copy); String ORIGINAL = foo[0]; String WRONG = "WRONG"; copy[0] = WRONG; assertNotEquals(WRONG, foo[0]); assertEquals(ORIGINAL, foo[0]); }
@Test public void testCopyMatrix(){ String[][] ... |
User { public void setName(String name) { this.name = name; } User(String name, String surname, int id); @Override boolean equals(Object o); @Override int hashCode(); String getName(); void setName(String name); String getSurname(); void setSurname(String surname); int getId(); void setId(int id); } | @Test public void testMutabilityProblem(){ User foo = new User("foo", "bar", 0); MySet<User> users = new MySetHashMap<>(); users.add(foo); assertEquals(1, users.size()); assertTrue(users.isPresent(foo)); foo.setName("changed"); assertEquals(1, users.size()); assertFalse(users.isPresent(foo)); User copy = new User("foo"... |
MySetHashMap implements MySet<E> { @Override public int size() { return map.size(); } @Override void add(E element); @Override void remove(E element); @Override boolean isPresent(E element); @Override int size(); } | @Test public void testEmpty() { assertEquals(0, set.size()); assertTrue(set.isEmpty()); } |
MySetHashMap implements MySet<E> { @Override public void remove(E element) { map.delete(element); } @Override void add(E element); @Override void remove(E element); @Override boolean isPresent(E element); @Override int size(); } | @Test public void testRemove() { int n = set.size(); String element = "foo"; set.add(element); assertTrue(set.isPresent(element)); assertEquals(n + 1, set.size()); set.remove(element); assertFalse(set.isPresent(element)); assertEquals(n, set.size()); } |
HashFunctions { public static int hashLongToInt(long x) { return (int) x; } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int hashStringSumRevised(Str... | @Test public void testHashLongToInt(){ assertEquals(0, HashFunctions.hashLongToInt(0)); assertEquals(42, HashFunctions.hashLongToInt(42)); assertEquals(0, HashFunctions.hashLongToInt(0x1_00_00_00_00L)); assertEquals(5, HashFunctions.hashLongToInt(0x7_00_00_00_05L)); assertEquals(0, HashFunctions.hashLongToInt(0xFF_FF_0... |
HashFunctions { public static int hashLongToIntRevised(long x) { return (int) (x ^ (x >>> 32)); } static int nonUniformHash(int x); static int identityHash(int x); static int shiftedHash(int x); static int hashLongToInt(long x); static int hashLongToIntRevised(long x); static int hashStringSum(String x); static int ha... | @Test public void testHashLongToIntRevised(){ long x = 0b0001_0000_0000_0000_0000_0000_0000_0000_____0000_0000_0000_0000_0000_0000_0000_0000L; long w = 0b0001_0000_0000_0000_0000_0000_0000_0000_____0000_0000_0000_0000_0000_0000_0001_0000L; long z = 0b0001_0001_0000_0000_0000_0000_0000_0000_____0000_0000_0000_0000_0000_... |
UndirectedGraph implements Graph<V> { @Override public List<V> findPathBFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Queue<V> queue = new ArrayDeque<>(); Map<V,V> bestParent = new HashMap<>(); queue.add(st... | @Test public void testShortestPath_simple() { Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathBFS(1, 2); assertNotNull(path); assertEquals(2, path.size()); assertEquals(1, (int) path.get(0)); assertEquals(2, (int) path.get(1)); }
@Test public void testShortestPath_complex() { Graph<Integer> gra... |
UndirectedGraph implements Graph<V> { @Override public List<V> findPathDFS(V start, V end) { if(! graph.containsKey(start) || ! graph.containsKey(end)){ return null; } if(start.equals(end)){ throw new IllegalArgumentException(); } Set<V> alreadyVisited = new HashSet<>(); Deque<V> stack = new ArrayDeque<>(); dfs(alread... | @Test public void testNoPathDFS(){ Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathDFS(10, 4); assertNull(path); } |
UndirectedGraph implements Graph<V> { @Override public Set<V> findConnected(V vertex) { if(! graph.containsKey(vertex)){ return null; } Set<V> connected = new HashSet<>(); findConnected(connected, vertex); return connected; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getN... | @Test public void testConnected(){ Graph<Integer> graph = createGraph(); Set<Integer> left = graph.findConnected(3); Set<Integer> right = graph.findConnected(10); assertEquals(8, left.size()); assertEquals(2, right.size()); } |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 9