method2testcases
stringlengths 118
6.63k
|
---|
### Question:
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 getAnonymousGroupName(); }### Answer:
@Test public void shouldGetPartitionAddress() { assertThat(NamingUtils.getPartitionAddress("testAddress", 0)).isEqualTo("testAddress-0"); }
@Test(expected = NullPointerException.class) public void shouldNotAcceptNullAddressToGetPartitionAddress() { NamingUtils.getPartitionAddress(null, 0); } |
### Question:
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(); }### Answer:
@Test public void shouldGetNameForPartition() { String name = "test-name"; ArtemisProducerDestination destination = new ArtemisProducerDestination(name); assertThat(destination.getNameForPartition(0)).isEqualTo(getPartitionAddress(name, 0)); } |
### Question:
ArtemisConsumerDestination implements ConsumerDestination { @Override public String getName() { return name; } ArtemisConsumerDestination(String name); @Override String getName(); @Override String toString(); }### Answer:
@Test public void shouldGetName() { String name = "test-name"; ArtemisConsumerDestination destination = new ArtemisConsumerDestination(name); assertThat(destination.getName()).isEqualTo(name); } |
### Question:
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 = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }### Answer:
@Test public void shouldCreateAddress() throws Exception { ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createAddress(address.toString(), artemisCommonProperties); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verify(mockClientSession).start(); verify(mockClientSession).createAddress(address, MULTICAST, true); verify(mockClientSession).stop(); verify(mockClientSession, times(0)).queueQuery(any(SimpleString.class)); verify(mockClientSession, times(0)).createMessage(anyBoolean()); }
@Test public void shouldCreateAddressWithCredentials() throws Exception { given(mockServerLocator.isPreAcknowledge()).willReturn(true); given(mockServerLocator.getAckBatchSize()).willReturn(1); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, "user", "pass"); manager.createAddress(address.toString(), artemisCommonProperties); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession("user", "pass", true, false, false, true, 1); verify(mockClientSession).start(); verify(mockClientSession).createAddress(address, MULTICAST, true); verify(mockClientSession).stop(); verify(mockClientSession, times(0)).queueQuery(any(SimpleString.class)); verify(mockClientSession, times(0)).createMessage(anyBoolean()); }
@Test public void shouldNotCreateAddressIfOneExists() throws Exception { given(mockAddressQuery.isExists()).willReturn(true); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createAddress(address.toString(), artemisCommonProperties); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verify(mockClientSession).start(); verify(mockClientSession).stop(); verify(mockClientSession, times(0)).createAddress(any(), any(RoutingType.class), anyBoolean()); verify(mockClientSession, times(0)).queueQuery(any(SimpleString.class)); verify(mockClientSession, times(0)).createMessage(anyBoolean()); }
@Test public void shouldFailToCreateAddress() throws Exception { given(mockServerLocator.createSessionFactory()).willThrow(new RuntimeException("test")); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); try { manager.createAddress(address.toString(), artemisCommonProperties); fail("Provisioning exception was expected"); } catch (ProvisioningException e) { String message = String.format("Failed to create address '%s'", address); assertThat(e.getMessage()).contains(message); } } |
### Question:
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 (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }### Answer:
@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(mockClientSession).createSharedQueue(address, MULTICAST, queue, true); }
@Test public void shouldCreateQueueWithCredentials() throws Exception { given(mockServerLocator.isPreAcknowledge()).willReturn(true); given(mockServerLocator.getAckBatchSize()).willReturn(1); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, "user", "pass"); manager.createQueue(address.toString(), queue.toString()); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession("user", "pass", true, false, false, true, 1); verify(mockClientSession).createSharedQueue(address, MULTICAST, queue, true); }
@Test public void shouldNotCreateQueueIfOneAlreadyExists() throws Exception { given(mockQueueQuery.getAddress()).willReturn(address); given(mockQueueQuery.isExists()).willReturn(true); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createQueue(address.toString(), queue.toString()); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verify(mockClientSession, times(0)).createSharedQueue(any(), any(RoutingType.class), any(), anyBoolean()); }
@Test public void shouldFailToCreateQueue() throws Exception { given(mockServerLocator.createSessionFactory()).willThrow(new RuntimeException("test")); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); try { manager.createQueue(address.toString(), queue.toString()); fail("Provisioning exception was expected"); } catch (ProvisioningException e) { String message = String.format("Failed to create queue '%s' with address '%s'", queue, address); assertThat(e.getMessage()).contains(message); } }
@Test public void shouldFailToCreateQueueIfOneAlreadyExistsUnderAnotherAddress() { SimpleString anotherAddress = toSimpleString("another-address-name"); given(mockQueueQuery.getAddress()).willReturn(anotherAddress); given(mockQueueQuery.isExists()).willReturn(true); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); try { manager.createQueue(address.toString(), queue.toString()); fail("Provisioning exception was expected"); } catch (ProvisioningException e) { String message = String.format( "Failed to create queue '%s' with address '%s'. Queue already exists under another address '%s'", queue, address, anotherAddress); assertThat(e.getMessage()).contains(message); } } |
### Question:
ArtemisProvisioningProvider implements ProvisioningProvider<
ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address,
ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group,
ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }### Answer:
@Test public void shouldProvisionUnpartitionedConsumer() { ConsumerDestination destination = provider.provisionConsumerDestination(address, null, mockConsumerProperties); assertThat(destination).isInstanceOf(ArtemisConsumerDestination.class); assertThat(destination.getName()).isEqualTo(address); verify(mockArtemisBrokerManager).createAddress(address, mockArtemisConsumerProperties); }
@Test public void shouldProvisionPartitionedConsumer() { given(mockConsumerProperties.isPartitioned()).willReturn(true); given(mockConsumerProperties.getInstanceIndex()).willReturn(0); ConsumerDestination destination = provider.provisionConsumerDestination(address, null, mockConsumerProperties); String partitionedAddress = String.format("%s-0", address); assertThat(destination).isInstanceOf(ArtemisConsumerDestination.class); assertThat(destination.getName()).isEqualTo(partitionedAddress); verify(mockArtemisBrokerManager).createAddress(partitionedAddress, mockArtemisConsumerProperties); } |
### Question:
ListenerContainerFactory { public AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName) { DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer(); listenerContainer.setConnectionFactory(connectionFactory); listenerContainer.setPubSubDomain(true); listenerContainer.setDestinationName(topic); listenerContainer.setSubscriptionName(subscriptionName); listenerContainer.setSessionTransacted(true); listenerContainer.setSubscriptionDurable(true); listenerContainer.setSubscriptionShared(true); return listenerContainer; } ListenerContainerFactory(ConnectionFactory connectionFactory); AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName); }### Answer:
@Test public void shouldGetListenerContainer() { ListenerContainerFactory factory = new ListenerContainerFactory(mockConnectionFactory); AbstractMessageListenerContainer container = factory.getListenerContainer("testTopic", "testSubscription"); assertThat(container.getConnectionFactory()).isEqualTo(mockConnectionFactory); assertThat(container.getDestinationName()).isEqualTo("testTopic"); assertThat(container.isPubSubDomain()).isTrue(); assertThat(container.getSubscriptionName()).isEqualTo("testSubscription"); assertThat(container.isSessionTransacted()).isTrue(); assertThat(container.isSubscriptionDurable()).isTrue(); assertThat(container.isSubscriptionShared()).isTrue(); } |
### Question:
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); static String getAnonymousGroupName(); }### Answer:
@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 = NullPointerException.class) public void shouldNotAcceptNullGroupToGetQueueName() { NamingUtils.getQueueName("testAddress", null); } |
### Question:
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("=", ""); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }### Answer:
@Test public void shouldGetAnonymousQueueName() { assertThat(NamingUtils.getAnonymousGroupName()).hasSize(32) .startsWith("anonymous-"); } |
### Question:
ArtemisMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>,
ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageHandler createProducerMessageHandler(ProducerDestination destination, ExtendedProducerProperties<ArtemisProducerProperties> properties, MessageChannel errorChannel) { logger.debug("Creating producer message handler for '" + destination + "'"); JmsSendingMessageHandler handler = Jms.outboundAdapter(connectionFactory) .destination(message -> getMessageDestination(message, destination)) .configureJmsTemplate(templateSpec -> templateSpec.pubSubDomain(true)) .get(); handler.setApplicationContext(getApplicationContext()); handler.setBeanFactory(getBeanFactory()); return handler; } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider,
ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); @Override ArtemisConsumerProperties getExtendedConsumerProperties(String channelName); @Override ArtemisProducerProperties getExtendedProducerProperties(String channelName); @Override String getDefaultsPrefix(); @Override Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass(); }### Answer:
@Test public void shouldCreateProducerMessageHandler() { MessageHandler handler = binder.createProducerMessageHandler(null, null, null); assertThat(handler).isInstanceOf(JmsSendingMessageHandler.class); } |
### Question:
ArtemisMessageChannelBinder extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>,
ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) { logger.debug("Creating consumer endpoint for '{" + destination + "}' with a group '{" + group + "}'"); if (!StringUtils.hasText(group)) { group = getAnonymousGroupName(); } String subscriptionName = getQueueName(destination.getName(), group); ListenerContainerFactory listenerContainerFactory = new ListenerContainerFactory(connectionFactory); AbstractMessageListenerContainer listenerContainer = listenerContainerFactory .getListenerContainer(destination.getName(), subscriptionName); if (properties.getMaxAttempts() == 1) { return Jms.messageDrivenChannelAdapter(listenerContainer).get(); } RetryTemplate retryTemplate = buildRetryTemplate(properties); ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties); RetryableChannelPublishingJmsMessageListener listener = new RetryableChannelPublishingJmsMessageListener(retryTemplate, errorInfrastructure.getRecoverer()); listener.setExpectReply(false); return new JmsMessageDrivenEndpoint(listenerContainer, listener); } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider,
ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); @Override ArtemisConsumerProperties getExtendedConsumerProperties(String channelName); @Override ArtemisProducerProperties getExtendedProducerProperties(String channelName); @Override String getDefaultsPrefix(); @Override Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass(); }### Answer:
@Test public void shouldCreateRegularConsumerEndpoint() { given(mockConsumerProperties.getMaxAttempts()).willReturn(1); ArtemisConsumerDestination destination = new ArtemisConsumerDestination("test-destination"); MessageProducer producer = binder.createConsumerEndpoint(destination, "test-group", mockConsumerProperties); assertThat(producer).isInstanceOf(JmsMessageDrivenEndpoint.class); JmsMessageDrivenEndpoint endpoint = (JmsMessageDrivenEndpoint) producer; assertThat(endpoint.getListener()).isNotInstanceOf(RetryableChannelPublishingJmsMessageListener.class); }
@Test public void shouldCreateRetryableConsumerEndpoint() { given(mockConsumerProperties.getMaxAttempts()).willReturn(2); ArtemisConsumerDestination destination = new ArtemisConsumerDestination("test-destination"); MessageProducer producer = binder.createConsumerEndpoint(destination, "test-group", mockConsumerProperties); assertThat(producer).isInstanceOf(JmsMessageDrivenEndpoint.class); ChannelPublishingJmsMessageListener listener = ((JmsMessageDrivenEndpoint) producer).getListener(); assertThat(listener).isInstanceOf(RetryableChannelPublishingJmsMessageListener.class); assertThat(listener.getComponentType()).isEqualTo("jms:message-driven-channel-adapter"); } |
### Question:
ArtemisProducerDestination implements ProducerDestination { @Override public String getName() { return name; } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); }### Answer:
@Test public void shouldGetName() { String name = "test-name"; ArtemisProducerDestination destination = new ArtemisProducerDestination(name); assertThat(destination.getName()).isEqualTo(name); } |
### Question:
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.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold,
Map<String, Integer> predictions); static void main(String[] args); }### Answer:
@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 readLabelsFromFileWrong1() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-wrong1.txt")); }
@Test(expected = IllegalArgumentException.class) public void readLabelsFromFileWrong2() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-wrong2.txt")); }
@Test(expected = IllegalArgumentException.class) public void readLabelsFromFileWrong3() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-wrong3.txt")); } |
### Question:
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 null"); } if (gold.isEmpty()) { throw new IllegalArgumentException("Parameter 'gold' is an empty map"); } if (predictions.isEmpty()) { throw new IllegalArgumentException("Parameter 'predictions' is an empty map"); } if (!(gold.keySet().containsAll(predictions.keySet()) && predictions.keySet() .containsAll(gold.keySet()))) { throw new IllegalArgumentException( "Gold set and predictions contain different instance IDs"); } Set<String> correctPredictions = new TreeSet<>(); Set<String> wrongPredictions = new TreeSet<>(); for (String id : gold.keySet()) { int goldLabel = gold.get(id); int predictedLabel = predictions.get(id); if (goldLabel == predictedLabel) { correctPredictions.add(id); } else { wrongPredictions.add(id); } } return ((double) correctPredictions.size()) / ((double) correctPredictions.size() + wrongPredictions.size()); } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold,
Map<String, Integer> predictions); static void main(String[] args); }### Answer:
@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, predictions1), 0.01); Map<String, Integer> predictions2 = Scorer .readLabelsFromFile(getFileFromResources("test-predictions2.txt")); assertEquals(1.0, Scorer.computeAccuracy(gold, predictions2), 0.01); Map<String, Integer> predictions3 = Scorer .readLabelsFromFile(getFileFromResources("test-predictions3.txt")); assertEquals(0.0, Scorer.computeAccuracy(gold, predictions3), 0.01); } |
### Question:
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(XMLStreamReader2 reader); @Override void onCharacter(XMLStreamReader2 reader); GrobidResponse getResponse(); }### Answer:
@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.GrobidResponse structures = target.getResponse(); assertThat(structures.getAtitle(), is("This si the end of the world")); assertThat(structures.getFirstAuthor(), is("Foppiano")); }
@Test public void testParsingPublication2_shouldWork() throws Exception { InputStream inputStream = this.getClass().getResourceAsStream("/sample.grobid-2.xml"); XMLStreamReader2 reader = (XMLStreamReader2) inputFactory.createXMLStreamReader(inputStream); StaxUtils.traverse(reader, target); GrobidResponseStaxHandler.GrobidResponse structures = target.getResponse(); assertThat(structures.getFirstAuthorMonograph(), is("Gupta")); }
@Test public void testParsingPublication3_shouldWork() throws Exception { InputStream inputStream = this.getClass().getResourceAsStream("/sample.grobid-3.xml"); XMLStreamReader2 reader = (XMLStreamReader2) inputFactory.createXMLStreamReader(inputStream); StaxUtils.traverse(reader, target); GrobidResponseStaxHandler.GrobidResponse structures = target.getResponse(); assertThat(structures.getAtitle(), is("This si the end of the world")); assertThat(structures.getFirstAuthor(), is("Foppiano")); } |
### Question:
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 (JsonGenerationException | JsonMappingException e) { LOGGER.error("The input line cannot be processed\n " + inputLine + "\n ", e); } catch (IOException e) { LOGGER.error("Some serious error when deserialize the JSON object: \n" + inputLine, e); } return null; } void load(String input, Consumer<IstexData> closure); void load(InputStream input, Consumer<IstexData> closure); IstexData fromJson(String inputLine); }### Answer:
@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()))); assertThat(metadata.getCorpusName(), is("bmj")); assertThat(metadata.getIstexId(), is("052DFBD14E0015CA914E28A0A561675D36FFA2CC")); assertThat(metadata.getDoi(), hasSize(1)); assertThat(metadata.getDoi().get(0), is("10.1136/sti.53.1.56")); assertThat(metadata.getArk(), hasSize(1)); assertThat(metadata.getArk().get(0), is("ark:/67375/NVC-W015BZV5-Q")); assertThat(metadata.getPmid(), hasSize(1)); assertThat(metadata.getPmid().get(0), is("557360")); assertThat(metadata.getPii(), hasSize(1)); assertThat(metadata.getPii().get(0), is("123")); } |
### Question:
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(String input, Consumer<IstexData> closure); void load(InputStream input, Consumer<IstexData> closure); IstexData fromJson(String inputLine); }### Answer:
@Test public void test3() throws Exception { target.load( new GZIPInputStream(this.getClass().getResourceAsStream("/sample-istex-ids.json.gz")), unpaidWallMetadata -> System.out.println(unpaidWallMetadata.getDoi() )); } |
### Question:
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); void load(InputStream input, Consumer<PmidData> closure); PmidData fromCSV(String inputLine); }### Answer:
@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 ("")); } |
### Question:
SupplyLocationBulkUploadController { public List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations) { return this.service.saveSupplyLocationsZipContains504(locations); } @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository); @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository, SupplyLocationService service); @RequestMapping(value = "/bulk/supplyLocations", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) void upload(@RequestBody List<SupplyLocation> locations); @RequestMapping(value = "/purge", method = RequestMethod.POST) void purge(); List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations); }### Answer:
@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().isEqualTo(1); assertThat(controller.uploadFitleredLocations(inputLocations).get(0).getZip()).isEqualTo("504"); } |
### Question:
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); }### Answer:
@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 allowsKeyAndValueWhenNeitherIsNull() { assertTrue(generator.okToAdd(new Object(), new Object())); } |
### Question:
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<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted(
Collection<Weighted<T>> items,
SourceOfRandomness random); }### Answer:
@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); assertEquals("charlie", Items.choose(names, random)); } |
### Question:
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 += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted(
Collection<Weighted<T>> items,
SourceOfRandomness random); }### Answer:
@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(first), random)); }
@Test public void choosingFirstOfManyWeightedItems() { when(random.nextInt(9)).thenReturn(0).thenReturn(1); assertEquals("a", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("a", Items.chooseWeighted(asList(first, second, third), random)); }
@Test public void choosingMiddleOfManyWeightedItems() { when(random.nextInt(9)).thenReturn(2).thenReturn(3).thenReturn(4); assertEquals("b", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("b", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("b", Items.chooseWeighted(asList(first, second, third), random)); }
@Test public void choosingLastOfManyWeightedItems() { when(random.nextInt(9)).thenReturn(5).thenReturn(6).thenReturn(7).thenReturn(8); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); } |
### Question:
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, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem(
SourceOfRandomness random,
List<T> target,
Shrink<T> shrink); static boolean isDistinct(List<T> target); }### Answer:
@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 public void removalsFromAnEmptyList() { assertEquals(emptyList(), Lists.removeFrom(emptyList(), 1)); }
@Test public void singleRemovalsFromASingletonList() { assertEquals(singletonList(emptyList()), Lists.removeFrom(singletonList('a'), 1)); }
@Test public void singleRemovalsFromADoubletonList() { assertEquals( newHashSet(singletonList('a'), singletonList('b')), newHashSet(Lists.removeFrom(newArrayList('a', 'b'), 1))); }
@Test public void doubleRemovalsFromADoubletonList() { assertEquals(singletonList(emptyList()), Lists.removeFrom(newArrayList('a', 'b'), 2)); }
@Test public void tooManyRemovalsFromADoubletonList() { assertEquals(emptyList(), Lists.removeFrom(newArrayList('a', 'b'), 3)); } |
### Question:
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(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem(
SourceOfRandomness random,
List<T> target,
Shrink<T> shrink); static boolean isDistinct(List<T> target); }### Answer:
@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, 5); }); assertEquals( newArrayList( newArrayList(4, 2, 3), newArrayList(5, 2, 3), newArrayList(1, 4, 3), newArrayList(1, 5, 3), newArrayList(1, 2, 4), newArrayList(1, 2, 5) ), shrinks); } |
### Question:
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( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } private Lambdas(); static T makeLambda(
Class<T> lambdaType,
Generator<U> returnValueGenerator,
GenerationStatus status); }### Answer:
@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.getProperty("java.version")); @SuppressWarnings("unchecked") Predicate<Integer> another = makeLambda(Predicate.class, returnValueGenerator, status); boolean firstResult = predicate.test(4); boolean secondResult = another.test(4); assertEquals(firstResult || secondResult, predicate.or(another).test(4)); }
@Test public void equalsBasedOnIdentity() { Predicate<?> duplicate = makeLambda(Predicate.class, returnValueGenerator, status); assertEquals(predicate, predicate); assertEquals(duplicate, duplicate); assertNotEquals(predicate, duplicate); assertNotEquals(duplicate, predicate); } |
### Question:
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; }### Answer:
@Test public void stringifying() { assertEquals("[1 = 2]", new Pair<>(1, 2).toString()); } |
### Question:
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(
BigDecimal max,
BigDecimal start); static Iterable<Integer> halving(int start); }### Answer:
@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( BigInteger.valueOf(-5), BigInteger.valueOf(-7), BigInteger.valueOf(-8), BigInteger.valueOf(-9)), newArrayList(Sequences.halvingIntegral(BigInteger.TEN.negate(), BigInteger.ZERO))); }
@Test public void callingNextOutOfSequenceOnHalvingBigIntegers() { Iterator<BigInteger> i = Sequences.halvingIntegral(BigInteger.ZERO, BigInteger.ZERO).iterator(); i.next(); thrown.expect(NoSuchElementException.class); i.next(); } |
### Question:
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(
BigDecimal max,
BigDecimal start); static Iterable<Integer> halving(int start); }### Answer:
@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.valueOf(-5), BigDecimal.valueOf(-8), BigDecimal.valueOf(-9), BigDecimal.TEN.negate()), newArrayList(Sequences.halvingDecimal(BigDecimal.TEN.negate(), BigDecimal.ZERO))); }
@Test public void callingNextOutOfSequenceOnHalvingBigDecimals() { Iterator<BigDecimal> i = Sequences.halvingDecimal(BigDecimal.ZERO, BigDecimal.ZERO).iterator(); i.next(); thrown.expect(NoSuchElementException.class); i.next(); } |
### Question:
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 start); static Iterable<Integer> halving(int start); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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(RetentionPolicy.SOURCE)); } |
### Question:
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); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); Generator<?> composed(int index); int numberOfComposedGenerators(); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); @Override void configure(AnnotatedElement element); @Override void addComponentGenerators(List<Generator<?>> newComponents); }### Answer:
@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.canShrink(8)).thenReturn(false); when(second.canShrink(8)).thenReturn(false); when(third.canShrink(8)).thenReturn(false); assertFalse(composite.canShrink(8)); } |
### Question:
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(
SourceOfRandomness random,
GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); }### Answer:
@Test public void capabilityOfShrinkingNonArray() { assertFalse(intArrayGenerator.canShrink(3)); }
@Test public void capabilityOfShrinkingArrayOfIdenticalComponentType() { assertTrue(intArrayGenerator.canShrink(new int[0])); }
@Test public void capabilityOfShrinkingArrayOfEquivalentWrapperComponentType() { assertFalse(intArrayGenerator.canShrink(new Integer[0])); } |
### Question:
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 (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange(
T min,
T max); static T leastMagnitude(
T min,
T max,
T zero); }### Answer:
@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(Integer.valueOf(4), Comparables.leastMagnitude(4, null, 0)); }
@Test public void leastMagnitudeNegativeMaxOnly() { assertEquals(Integer.valueOf(-2), Comparables.leastMagnitude(null, -2, 0)); }
@Test public void leastMagnitudePositiveMaxOnly() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(null, 5, 0)); }
@Test public void leastMagnitudeBothLessThanZero() { assertEquals(Integer.valueOf(-1), Comparables.leastMagnitude(-4, -1, 0)); }
@Test public void leastMagnitudeBothGreaterThanZero() { assertEquals(Integer.valueOf(5), Comparables.leastMagnitude(5, 7, 0)); }
@Test public void leastMagnitudeStraddlingZero() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(-2, 4, 0)); } |
### Question:
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); }### Answer:
@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(IllegalArgumentException.class); distro.sample(1 + ulp(1), random); }
@Test public void sampleWithCertainProbability() { assertEquals(0, distro.sample(1, random)); }
@Test public void sampleWithNonCertainProbability() { when(random.nextDouble()).thenReturn(0.88); assertEquals(10, distro.sample(0.2, random)); } |
### Question:
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); }### Answer:
@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, distro.probabilityOfMean(6), 0); } |
### Question:
GeometricDistribution { public int sampleWithMean(double mean, SourceOfRandomness random) { return sample(probabilityOfMean(mean), random); } int sampleWithMean(double mean, SourceOfRandomness random); }### Answer:
@Test public void sampleWithMean() { when(random.nextDouble()).thenReturn(0.76); assertEquals(8, distro.sampleWithMean(6, random)); } |
### Question:
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> findConstructor(
Class<T> type,
Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor(
Class<T> type,
Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor(
Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType(
AnnotatedElement e,
Class<T> type); static Method findMethod(
Class<?> target,
String methodName,
Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField(
Field field,
Object target,
Object value,
boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes(
AnnotatedType annotatedType); }### Answer:
@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(NoSuchMethodException.class.getName()); assertNull(findConstructor(Integer.class, Object.class)); } |
### Question:
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 Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor(
Class<T> type,
Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor(
Class<T> type,
Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor(
Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType(
AnnotatedElement e,
Class<T> type); static Method findMethod(
Class<?> target,
String methodName,
Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField(
Field field,
Object target,
Object value,
boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes(
AnnotatedType annotatedType); }### Answer:
@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.expectMessage(NoSuchMethodException.class.getName()); assertNull(findDeclaredConstructor(Integer.class, Object.class)); } |
### Question:
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); }### Answer:
@Test public void versusCharsetThatDoesNotSupportEncoding() { Charset noEncoding; try { noEncoding = Charset.forName("ISO-2022-CN"); } catch (UnsupportedCharsetException testNotValid) { return; } thrown.expect(IllegalArgumentException.class); CodePoints.forCharset(noEncoding); } |
### Question:
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>) constructors[0]; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor(
Class<T> type,
Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor(
Class<T> type,
Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor(
Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType(
AnnotatedElement e,
Class<T> type); static Method findMethod(
Class<?> target,
String methodName,
Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField(
Field field,
Object target,
Object value,
boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes(
AnnotatedType annotatedType); }### Answer:
@Test public void findingSingleAccessibleConstructorSuccessfully() { Constructor<Object> ctor = singleAccessibleConstructor(Object.class); assertEquals(0, ctor.getParameterTypes().length); }
@Test public void rejectsFindingSingleAccessibleConstructorOnNonConformingClass() { thrown.expect(ReflectionException.class); thrown.expectMessage(Integer.class + " needs a single accessible constructor"); singleAccessibleConstructor(Integer.class); } |
### Question:
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); static Constructor<T> findDeclaredConstructor(
Class<T> type,
Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor(
Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType(
AnnotatedElement e,
Class<T> type); static Method findMethod(
Class<?> target,
String methodName,
Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField(
Field field,
Object target,
Object value,
boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes(
AnnotatedType annotatedType); }### Answer:
@Test public void invokingZeroArgConstructorQuietlyWrapsInstantiationException() { thrown.expect(ReflectionException.class); thrown.expectMessage(InstantiationException.class.getName()); instantiate(ZeroArgInstantiationProblematic.class); }
@Test public void invokingZeroArgConstructorQuietlyWrapsIllegalAccessException() { thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); instantiate(ZeroArgIllegalAccessProblematic.class); }
@Test public void invokingZeroArgConstructorPropagatesExceptionsRaisedByConstructor() { thrown.expect(IllegalStateException.class); instantiate(InvocationTargetProblematic.class); }
@Test public void invokingNonZeroArgConstructorQuietlyWrapsInstantiationException() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(InstantiationException.class.getName()); instantiate(MultiArgInstantiationProblematic.class.getConstructor(int.class), 2); }
@Test public void invokingNonZeroArgConstructorQuietlyWrapsIllegalAccessException() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); instantiate(MultiArgIllegalAccessProblematic.class.getDeclaredConstructor(int.class), 2); }
@Test public void invokingNonZeroArgConstructorQuietlyPropagatesIllegalArgumentException() throws Exception { thrown.expect(IllegalArgumentException.class); instantiate(Integer.class.getDeclaredConstructor(int.class), "2"); }
@Test public void invokingNonZeroArgConstructorWrapsExceptionsRaisedByConstructor() throws Exception { thrown.expect(ReflectionException.class); thrown.expectMessage(IndexOutOfBoundsException.class.getName()); instantiate(InvocationTargetProblematic.class.getConstructor(int.class), 2); } |
### Question:
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> findConstructor(
Class<T> type,
Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor(
Class<T> type,
Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor(
Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType(
AnnotatedElement e,
Class<T> type); static Method findMethod(
Class<?> target,
String methodName,
Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField(
Field field,
Object target,
Object value,
boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes(
AnnotatedType annotatedType); }### Answer:
@Test public void findingNonExistentMethodQuietlyWrapsNoSuchMethodException() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); findMethod(getClass(), "foo"); } |
### Question:
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 && index < current.previousCount + current.size()) return current.low + index - current.previousCount; else if (index < current.previousCount) max = midpoint - 1; else min = midpoint + 1; } throw new IndexOutOfBoundsException(String.valueOf(index)); } CodePoints(); int at(int index); int size(); boolean contains(int codePoint); static CodePoints forCharset(Charset c); }### Answer:
@Test public void lowIndex() { thrown.expect(IndexOutOfBoundsException.class); new CodePoints().at(-1); }
@Test public void highIndex() { thrown.expect(IndexOutOfBoundsException.class); new CodePoints().at(0); } |
### Question:
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,
Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor(
Class<T> type,
Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor(
Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType(
AnnotatedElement e,
Class<T> type); static Method findMethod(
Class<?> target,
String methodName,
Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField(
Field field,
Object target,
Object value,
boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes(
AnnotatedType annotatedType); }### Answer:
@Test public void invokingMethodQuietlyWrapsIllegalAccessException() throws Exception { Method method = ZeroArgIllegalAccessProblematic.class.getDeclaredMethod("foo"); thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); invoke(method, new ZeroArgIllegalAccessProblematic(0)); } |
### Question:
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 Constructor<T> findConstructor(
Class<T> type,
Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor(
Class<T> type,
Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor(
Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType(
AnnotatedElement e,
Class<T> type); static Method findMethod(
Class<?> target,
String methodName,
Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField(
Field field,
Object target,
Object value,
boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes(
AnnotatedType annotatedType); }### Answer:
@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(Foo.class, "noneSuch"); } |
### Question:
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)) { singleAbstractMethod = each; ++abstractCount; } } return abstractCount == 1 ? singleAbstractMethod : null; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor(
Class<T> type,
Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor(
Class<T> type,
Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor(
Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType(
AnnotatedElement e,
Class<T> type); static Method findMethod(
Class<?> target,
String methodName,
Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField(
Field field,
Object target,
Object value,
boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes(
AnnotatedType annotatedType); }### Answer:
@Test public void aClassIsNotASingleAbstractMethodType() { assertNull(singleAbstractMethodOf(String.class)); }
@Test public void anInterfaceWithNoMethodsIsNotASingleAbstractMethodType() { assertNull(singleAbstractMethodOf(Serializable.class)); }
@Test public void anInterfaceWithASingleAbstractMethodIsASingleAbstractMethodType() throws Exception { assertEquals( Comparator.class.getMethod("compare", Object.class, Object.class), singleAbstractMethodOf(Comparator.class)); }
@Test public void anInterfaceThatOverridesEqualsIsNotASingleAbstractMethodType() throws Exception { assertNull(singleAbstractMethodOf(OverridingEquals.class)); }
@Test public void anInterfaceThatOverloadsEqualsCanBeASingleAbstractMethodType() throws Exception { assertEquals( OverloadingEquals.class.getMethod("equals", String.class), singleAbstractMethodOf(OverloadingEquals.class)); }
@Test public void anInterfaceThatOverloadsEqualsWithMoreThanOneParameterCanBeASingleAbstractMethodType() throws Exception { assertEquals( OverloadingEqualsWithMoreParameters.class.getMethod("equals", Object.class, Object.class), singleAbstractMethodOf(OverloadingEqualsWithMoreParameters.class)); }
@Test public void anInterfaceThatOverloadsEqualsWithMixedParameterTypesIsNotASingleAbstractMethodType() throws Exception { assertEquals( OverloadingEqualsWithMixedParameterTypes.class.getMethod("equals", Object.class, String.class, int.class), singleAbstractMethodOf(OverloadingEqualsWithMixedParameterTypes.class)); }
@Test public void anInterfaceThatOverridesHashCodeIsNotASingleAbstractMethodType() throws Exception { assertNull(singleAbstractMethodOf(OverridingHashCode.class)); }
@Test public void anInterfaceThatOverloadsHashCodeCanBeASingleAbstractMethodType() throws Exception { assertEquals( OverloadingHashCode.class.getMethod("hashCode", Object.class), singleAbstractMethodOf(OverloadingHashCode.class)); }
@Test public void anInterfaceThatOverridesToStringIsNotASingleAbstractMethodType() throws Exception { assertNull(singleAbstractMethodOf(OverridingToString.class)); }
@Test public void anInterfaceThatOverloadsToStringCanBeASingleAbstractMethodType() throws Exception { assertEquals( OverloadingToString.class.getMethod("toString", Object.class), singleAbstractMethodOf(OverloadingToString.class)); } |
### Question:
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<T> findConstructor(
Class<T> type,
Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor(
Class<T> type,
Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor(
Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType(
AnnotatedElement e,
Class<T> type); static Method findMethod(
Class<?> target,
String methodName,
Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField(
Field field,
Object target,
Object value,
boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes(
AnnotatedType annotatedType); }### Answer:
@Test public void aClassIsNotAMarkerInterface() { assertFalse(isMarkerInterface(Object.class)); }
@Test public void anInterfaceWithAMethodIsNotAMarkerInterface() { assertFalse(isMarkerInterface(NotAMarker.class)); }
@Test public void anInterfaceWithNoMethodsButSuperMethodsIsNotAMarkerInterface() { assertFalse(isMarkerInterface(SubNotAMarker.class)); }
@Test public void anInterfaceThatOverridesEqualsIsAMarkerInterface() { assertTrue(isMarkerInterface(OverridingEquals.class)); }
@Test public void anInterfaceThatOverloadsEqualsIsNotAMarkerInterface() { assertFalse(isMarkerInterface(OverloadingEquals.class)); }
@Test public void anInterfaceThatOverloadsEqualsWithMoreThanOneParameterIsNotAMarkerInterface() { assertFalse( isMarkerInterface(OverloadingEqualsWithMoreParameters.class)); }
@Test public void anInterfaceThatOverloadsEqualsWithMixedParameterTypesIsNotAMarkerInterface() { assertFalse( isMarkerInterface(OverloadingEqualsWithMixedParameterTypes.class)); }
@Test public void anInterfaceThatOverridesHashCodeIsAMarkerInterface() { assertTrue(isMarkerInterface(OverridingHashCode.class)); }
@Test public void anInterfaceThatOverloadsHashCodeIsNotAMarkerInterface() { assertFalse(isMarkerInterface(OverloadingHashCode.class)); }
@Test public void anInterfaceThatOverridesToStringIsAMarkerInterface() { assertTrue(isMarkerInterface(OverridingToString.class)); }
@Test public void anInterfaceThatOverloadsToStringIsNotAMarkerInterface() { assertFalse(isMarkerInterface(OverloadingToString.class)); }
@Test public void anInterfaceWithOnlyDefaultMethodsIsAMarkerInterface() { assertTrue(isMarkerInterface(OnlyDefaultMethods.class)); } |
### Question:
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); }### Answer:
@Test public void sizeOfEmpty() { assertEquals(0, new CodePoints().size()); } |
### Question:
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 Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor(
Class<T> type,
Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor(
Class<T> type,
Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor(
Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType(
AnnotatedElement e,
Class<T> type); static Method findMethod(
Class<?> target,
String methodName,
Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField(
Field field,
Object target,
Object value,
boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes(
AnnotatedType annotatedType); }### Answer:
@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 { WithInaccessibleField target = new WithInaccessibleField(); setField(target.getClass().getDeclaredField("i"), target, 3, true); assertEquals(3, target.i); }
@Test public void settingInaccessibleFieldWithoutBypassingProtection() throws Exception { WithInaccessibleField target = new WithInaccessibleField(); thrown.expect(ReflectionException.class); thrown.expectMessage(IllegalAccessException.class.getName()); setField(target.getClass().getDeclaredField("i"), target, 4, false); } |
### Question:
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()); results.forEach(f -> f.setAccessible(true)); return results; } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor(
Class<T> type,
Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor(
Class<T> type,
Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor(
Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType(
AnnotatedElement e,
Class<T> type); static Method findMethod(
Class<?> target,
String methodName,
Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField(
Field field,
Object target,
Object value,
boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes(
AnnotatedType annotatedType); }### Answer:
@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 findingAllDeclaredFieldsOnAClassExcludesSynthetics() throws Exception { List<Field> fields = allDeclaredFieldsOf(Outer.Inner.class); assertEquals(1, fields.size()); assertThat(fields, hasItem(Outer.Inner.class.getDeclaredField("s"))); } |
### Question:
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); }### Answer:
@Test public void canOnlyGenerateNull() { VoidGenerator generator = new VoidGenerator(); Void value = generator.generate(null, null); assertNull(value); } |
### Question:
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> type,
Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor(
Class<T> type,
Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor(
Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf(
Class<? extends Annotation> annotationType,
String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType(
AnnotatedElement e,
Class<T> type); static Method findMethod(
Class<?> target,
String methodName,
Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField(
Field field,
Object target,
Object value,
boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes(
AnnotatedType annotatedType); }### Answer:
@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"); } |
### Question:
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(
SourceOfRandomness random,
BigInteger min,
BigInteger max); static long choose(SourceOfRandomness random, long min, long max); }### Answer:
@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, findNextPowerOfTwoLong((long) 1 << 61)); assertEquals((long) 1 << 62, findNextPowerOfTwoLong(1 + (long) 1 << 61)); } |
### Question:
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); } private Ranges(); static int checkRange(
Type type,
T min,
T max); static BigInteger choose(
SourceOfRandomness random,
BigInteger min,
BigInteger max); static long choose(SourceOfRandomness random, long min, long max); }### Answer:
@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); } } |
### Question:
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> getMessageMappings(Method method, Class<?> controller); static List<String> getSubscribeMappings(Method method, Class<?> controller); }### Answer:
@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("slashLongPath"); Method pathAttribute = ctrl.getDeclaredMethod("pathAttribute"); assertEquals(singletonList("/"), MappingsResolver.getRequestMappings(none, ctrl)); assertEquals(singletonList("/"), MappingsResolver.getRequestMappings(slash, ctrl)); assertEquals(singletonList("/path"), MappingsResolver.getRequestMappings(slashPath, ctrl)); assertEquals(singletonList("/long/path"), MappingsResolver.getRequestMappings(longPath, ctrl)); assertEquals(singletonList("/path/attr"), MappingsResolver.getRequestMappings(pathAttribute, ctrl)); }
@Test public void getRequestMappings_emptyClassAnnotation() throws NoSuchMethodException { Class<?> ctrl = EmptyAnnotatedController.class; Method none = ctrl.getDeclaredMethod("none"); Method test = ctrl.getDeclaredMethod("test"); assertEquals(singletonList("/"), MappingsResolver.getRequestMappings(none, ctrl)); assertEquals(singletonList("/test"), MappingsResolver.getRequestMappings(test, ctrl)); }
@Test public void getRequestMappings_classAnnotationWithPrefix() throws NoSuchMethodException { Class<?> ctrl = PrefixAnnotatedController.class; Method none = ctrl.getDeclaredMethod("none"); Method test = ctrl.getDeclaredMethod("test"); assertEquals(singletonList("/prefix"), MappingsResolver.getRequestMappings(none, ctrl)); assertEquals(singletonList("/prefix/test"), MappingsResolver.getRequestMappings(test, ctrl)); }
@Test public void getRequestMappings_childController_prefixOverride() throws NoSuchMethodException { Class<?> ctrl = PrefixOverrideChildController.class; Method none = ctrl.getMethod("none"); Method test = ctrl.getMethod("test"); assertEquals(singletonList("/child"), MappingsResolver.getRequestMappings(none, ctrl)); assertEquals(singletonList("/child/test"), MappingsResolver.getRequestMappings(test, ctrl)); }
@Test public void getRequestMappings_multiplePaths() throws NoSuchMethodException { Class<?> ctrl = MultiPathController.class; Method test = ctrl.getMethod("test"); List<String> expectedPaths = Arrays.asList("/path1/path3", "/path1/path4", "/path2/path3", "/path2/path4"); assertEquals(expectedPaths, MappingsResolver.getRequestMappings(test, ctrl)); } |
### Question:
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<Property> getProperties(Type type); }### Answer:
@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, CustomObject.class)); props.add(createFieldProperty("intField", int.class, CustomObject.class)); props.add(createFieldProperty("objField", Object.class, CustomObject.class)); props.add(new Property("genericField", List.class, new TypeToken<List<Integer>>() {}.getType(), CustomObject.class.getDeclaredField("genericField"))); assertEquals(props, new HashSet<>(scanner.getProperties(CustomObject.class))); }
@Test public void getFieldTypes_inheritedFields() throws NoSuchFieldException { Set<Property> props = new HashSet<>(); props.add(createFieldProperty("parentField", Float.class, Parent.class)); props.add(createFieldProperty("childField", Double.class, Child.class)); assertEquals(props, new HashSet<>(scanner.getProperties(Child.class))); }
@Test public void getFieldTypes_enum() throws NoSuchFieldException { Set<Property> props = new HashSet<>(); props.add(createFieldProperty("name", String.class, Enum.class)); props.add(createFieldProperty("ordinal", int.class, Enum.class)); props.add(createFieldProperty("intField", int.class, MyEnum.class)); props.add(createFieldProperty("doubleField", Double.class, MyEnum.class)); assertEquals(props, new HashSet<>(scanner.getProperties(MyEnum.class))); } |
### Question:
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); Predicate<? super Class<?>> getTypeFilter(); void setTypeFilter(Predicate<? super Class<?>> typeFilter); Predicate<? super Class<?>> getTypeInspectionFilter(); void setTypeInspectionFilter(Predicate<? super Class<?>> typeInspectionFilter); Function<Class<?>, Set<Class<?>>> getTypeMapper(); void setTypeMapper(Function<Class<?>, Set<Class<?>>> mapper); @Override Set<Class<?>> findTypesToDocument(Collection<? extends Type> rootTypes); }### Answer:
@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.findTypesToDocument(rootTypes), Character.class); }
@Test public void findTypes_customType() { Set<Type> rootTypes = Collections.singleton(Custom.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), Custom.class, Long.class); }
@Test public void findTypes_inheritedFields() { Set<Type> rootTypes = Collections.singleton(Child.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), Child.class, Double.class, Long.class); }
@Test public void findTypes_complexHierarchy() { Set<Type> rootTypes = Collections.singleton(TestRoot.class); assertSetEquals(explorer.findTypesToDocument(rootTypes), TestRoot.class, WithCustomObject.class, WithPrimitives.class, Custom.class, Long.class, String.class, int.class); } |
### Question:
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); }### Answer:
@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), ConcreteAImpl.class); }
@Test public void apply_interface() { assertEquals(mapper.apply(B.class), BImpl.class); assertEquals(mapper.apply(A.class), SimpleAImpl.class, ConcreteAImpl.class, BImpl.class); } |
### Question:
Defaults { public static Object defaultValueFor(@Nullable Class<?> type) { if (type == null) { return null; } return primitiveDefaults.get(type); } static Object defaultValueFor(@Nullable Class<?> type); }### Answer:
@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.class)); assertEquals(0.0, Defaults.defaultValueFor(double.class)); assertEquals(false, Defaults.defaultValueFor(boolean.class)); assertEquals('\0', Defaults.defaultValueFor(char.class)); }
@Test public void defaultValueFor_objects() { assertNull(Defaults.defaultValueFor(Integer.class)); assertNull(Defaults.defaultValueFor(Double.class)); assertNull(Defaults.defaultValueFor(Boolean.class)); assertNull(Defaults.defaultValueFor(String.class)); } |
### Question:
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.setDescription(JavadocHelper.getJavadocDescription(clazz).orElse(null)); return Optional.of(doc); } @NotNull @Override Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz,
@NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider); @NotNull @Override Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc,
TypeReferenceProvider typeReferenceProvider); }### Answer:
@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()); } |
### Question:
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)); return Optional.of(doc); } @NotNull @Override Optional<TypeDoc> buildTypeDocBase(@NotNull Class<?> clazz,
@NotNull TypeReferenceProvider typeReferenceProvider, @NotNull TemplateProvider templateProvider); @NotNull @Override Optional<PropertyDoc> buildPropertyDoc(Property property, TypeDoc parentDoc,
TypeReferenceProvider typeReferenceProvider); }### Answer:
@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"); Method getAge = Person.class.getDeclaredMethod("getAge"); Method getPhone = Person.class.getDeclaredMethod("getPhone"); Property nameProp = new Property("name", String.class, getName); nameProp.setField(nameField); nameProp.setGetter(getName); Property ageProp = new Property("age", Integer.class, getAge); ageProp.setField(ageField); ageProp.setGetter(getAge); Property phoneProp = new Property("phone", String.class, getPhone); phoneProp.setField(phoneField); phoneProp.setGetter(getPhone); Optional<TypeDoc> doc = reader.buildTypeDocBase(Person.class, typeReferenceProvider, c -> null); assertTrue(doc.isPresent()); TypeDoc typeDoc = doc.get(); Optional<PropertyDoc> maybeNameDoc = reader.buildPropertyDoc(nameProp, typeDoc, typeReferenceProvider); Optional<PropertyDoc> maybeAgeDoc = reader.buildPropertyDoc(ageProp, typeDoc, typeReferenceProvider); Optional<PropertyDoc> maybePhoneDoc = reader.buildPropertyDoc(phoneProp, typeDoc, typeReferenceProvider); assertTrue(maybeNameDoc.isPresent()); assertTrue(maybeAgeDoc.isPresent()); assertTrue(maybePhoneDoc.isPresent()); PropertyDoc nameDoc = maybeNameDoc.get(); PropertyDoc ageDoc = maybeAgeDoc.get(); PropertyDoc phoneDoc = maybePhoneDoc.get(); assertEquals("name", nameDoc.getName()); assertEquals("age", ageDoc.getName()); assertEquals("phone", phoneDoc.getName()); assertEquals("The name of this <code>Person</code>.", nameDoc.getDescription()); assertEquals("this person's age", ageDoc.getDescription()); assertEquals("Gets this person's <code>phone number</code>.", phoneDoc.getDescription()); } |
### Question:
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> getProperties(Type type); }### Answer:
@Test public void getProperties_primitive() { assertTrue(scanner.getProperties(int.class).isEmpty()); } |
### Question:
RestUserDetailsService implements UserDetailsManager { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return restTemplate.getForObject("/{0}", User.class, username); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }### Answer:
@Test public void testLoadUserByUsername() { server.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withHalJsonResponse("/user_jbloggs_GET.txt")); UserDetails userDetails = service.loadUserByUsername(USERNAME); assertNotNull(userDetails); } |
### Question:
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("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }### Answer:
@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(); } |
### Question:
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(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }### Answer:
@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(); } |
### Question:
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) ModelAndView displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal); static final String CONTROLLER_URL; static final String VIEW_ADD_SPANNER; static final String VIEW_SUCCESS; static final String VIEW_VALIDATION_FAIL; static final String MODEL_SPANNER; }### Answer:
@Test public void testPageDisplay() { ModelAndView response = controller.displayPage(); assertNotNull("no response", response); assertEquals("view", VIEW_ADD_SPANNER, response.getViewName()); } |
### Question:
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); } Spanner spanner = new Spanner(); spanner.setOwner(principal.getName()); spanner.setName(formData.getName()); spanner.setSize(formData.getSize()); spannersService.create(spanner); return new ModelAndView(VIEW_SUCCESS); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView addSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult, Principal principal); static final String CONTROLLER_URL; static final String VIEW_ADD_SPANNER; static final String VIEW_SUCCESS; static final String VIEW_VALIDATION_FAIL; static final String MODEL_SPANNER; }### Answer:
@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.addSpanner(formData, noErrors, currentUser); assertNotNull("no response", response); ArgumentCaptor<Spanner> spannerArgumentCaptor = ArgumentCaptor.forClass(Spanner.class); verify(spannersService).create(spannerArgumentCaptor.capture()); Spanner createdSpanner = spannerArgumentCaptor.getValue(); assertEquals("name", formData.getName(), createdSpanner.getName()); assertEquals("size", formData.getSize(), createdSpanner.getSize()); assertEquals("owner", currentUser.getName(), createdSpanner.getOwner()); assertEquals("view", VIEW_SUCCESS, response.getViewName()); }
@Test public void testValidationFail() { SpannerForm formData = new SpannerForm(); formData.setName("Keeley"); formData.setSize(12); BindingResult validationFail = new BeanPropertyBindingResult(formData, MODEL_SPANNER); validationFail.addError(new ObjectError("size", "TOO_BIG")); Principal currentUser = new TestingAuthenticationToken("user", "pass"); ModelAndView response = controller.addSpanner(formData, validationFail, currentUser); assertNotNull("no response", response); verify(spannersService, never()).update(any(Spanner.class)); assertEquals("view", VIEW_VALIDATION_FAIL, response.getViewName()); } |
### Question:
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 ModelAndView(VIEW_DETAIL_SPANNER, MODEL_SPANNER, spanner); } @RequestMapping(value = "/detailSpanner", method = RequestMethod.GET) ModelAndView displayDetail(@RequestParam Long id); static final String VIEW_DETAIL_SPANNER; static final String MODEL_SPANNER; }### Answer:
@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)response.getModelMap().get(MODEL_SPANNER); assertSpannerEquals(SPANNER, spannerInModel); }
@Test public void testSpannerNotFound() throws Exception { when(spannersService.findOne(SPANNER_ID)).thenReturn(null); try { controller.displayDetail(SPANNER_ID); fail("Expected: SpannerNotFoundException"); } catch(SpannerNotFoundException notFoundEx) { assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId()); } } |
### Question:
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; }### Answer:
@Test public void testHomePage() { String response = controller.index(); assertEquals("view name", VIEW_NOT_SIGNED_IN, response); } |
### Question:
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.encode(signupForm.getPassword()); UserDetails userDetails = new User(signupForm.getName(), hashedPassword, ENABLED); userDetailsManager.createUser(userDetails); log.info("Success! Created new user " + userDetails.getUsername()); return VIEW_SUCCESS; } @RequestMapping(value = CONTROLLER_URL) SignupForm displayPage(); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) String signup(@Valid @ModelAttribute SignupForm signupForm, Errors errors); static final String CONTROLLER_URL; static final String VIEW_SUCCESS; }### Answer:
@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 = populateForm(NAME, PASSWORD); Errors noErrors = new DirectFieldBindingResult(form, "form"); controller.signup(form, noErrors); verify(userDetailsManager).createUser(argThat(hasProperty("username", equalTo(NAME)))); }
@Test public void testPasswordHash() { given(passwordEncoder.encode(PASSWORD)).willReturn(HASHED_PASSWORD); SignupForm form = populateForm(NAME, PASSWORD); Errors noErrors = new DirectFieldBindingResult(form, "form"); controller.signup(form, noErrors); verify(userDetailsManager).createUser(argThat(hasProperty("password", equalTo(HASHED_PASSWORD)))); }
@Test public void testValidationFailIsLogged() { SignupForm invalidForm = populateForm(null, null); Errors errors = new DirectFieldBindingResult(invalidForm, "form"); errors.rejectValue("name", "Invalid name"); errors.rejectValue("password", "Invalid password"); controller.signup(invalidForm, errors); assertThat(sysOut.asString(), containsString("Oh no!")); }
@Test public void testSuccessIsLogged() { SignupForm form = populateForm(NAME, PASSWORD); Errors noErrors = new DirectFieldBindingResult(form, "form"); controller.signup(form, noErrors); assertThat(sysOut.asString(), containsString("Success!")); } |
### Question:
RestUserDetailsService implements UserDetailsManager { @Override public void createUser(UserDetails userDetails) { restTemplate.postForLocation("/", userDetails); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }### Answer:
@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(); } |
### Question:
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(MODEL_ATTRIBUTE_GREETING, greeting); return VIEW_DISPLAY_SPANNERS; } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }### Answer:
@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.get(MODEL_ATTRIBUTE_SPANNERS); assertNotNull(MODEL_ATTRIBUTE_SPANNERS + " is null", spannersInModel); assertEquals(SPANNERS, spannersInModel); }
@Test public void testTimeOfDayGreetingMorning() { when(currentTime.get()).thenReturn(LocalTime.of(9,0)); ModelMap model = new ModelMap(); controller.displaySpanners(model); String greeting = (String)model.get(MODEL_ATTRIBUTE_GREETING); assertEquals(GREETING_MORNING, greeting); }
@Test public void testTimeOfDayGreetingAfternoon() { when(currentTime.get()).thenReturn(LocalTime.of(14,0)); ModelMap model = new ModelMap(); controller.displaySpanners(model); String greeting = (String)model.get(MODEL_ATTRIBUTE_GREETING); assertEquals(GREETING_AFTERNOON, greeting); }
@Test public void testTimeOfDayGreetingEvening() { when(currentTime.get()).thenReturn(LocalTime.of(20,0)); ModelMap model = new ModelMap(); controller.displaySpanners(model); String greeting = (String)model.get(MODEL_ATTRIBUTE_GREETING); assertEquals(GREETING_EVENING, greeting); } |
### Question:
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); } spannersService.delete(spanner); return displaySpanners(model); } @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) String displaySpanners(ModelMap model); @RequestMapping(value = "/deleteSpanner", method = RequestMethod.GET) String deleteSpanner(@RequestParam Long id, ModelMap model); }### Answer:
@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 public void testDeleteSpannerNotFound() { when(spannersService.findOne(SPANNER_ID)).thenReturn(null); try { controller.deleteSpanner(SPANNER_ID, new ModelMap()); fail("Expected: SpannerNotFoundException"); } catch(SpannerNotFoundException notFoundEx) { assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId()); } } |
### Question:
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 SpannerNotFoundException(id); } SpannerForm initializedForm = new SpannerForm(spanner); return new ModelAndView(VIEW_EDIT_SPANNER, MODEL_SPANNER, initializedForm); } @Override void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.GET) ModelAndView displayPage(@RequestParam Long id); @RequestMapping(value = CONTROLLER_URL, method = RequestMethod.POST) ModelAndView updateSpanner(@Valid @ModelAttribute(MODEL_SPANNER) SpannerForm formData, BindingResult validationResult); static final String VIEW_EDIT_SPANNER; static final String VIEW_UPDATE_SUCCESS; static final String VIEW_VALIDATION_ERRORS; static final String MODEL_SPANNER; static final String CONTROLLER_URL; }### Answer:
@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 = (SpannerForm)response.getModelMap().get(MODEL_SPANNER); assertSpannerEquals(SPANNER, spannerFormData); }
@Test public void testSpannerNotFound() { when(spannersService.findOne(SPANNER_ID)).thenReturn(null); try { controller.displayPage(SPANNER_ID); fail("Expected: SpannerNotFoundException"); } catch(SpannerNotFoundException notFoundEx) { assertEquals("Exception spanner id", SPANNER_ID, notFoundEx.getSpannerId()); } } |
### Question:
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); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }### Answer:
@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(); } |
### Question:
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 loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }### Answer:
@Test public void testDeleteUser() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(DELETE)) .andRespond(withStatus(HttpStatus.OK)); service.deleteUser(USERNAME); server.verify(); } |
### Question:
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 false; } } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }### Answer:
@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.expect(requestTo("/" + USERNAME)).andExpect(method(GET)) .andRespond(withStatus(HttpStatus.NOT_FOUND)); boolean userExists = service.userExists(USERNAME); assertFalse(userExists); } |
### Question:
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, requestEntity, Void.class, username); } RestUserDetailsService(RestTemplateBuilder builder,
@Value("${app.service.url.users}") String rootUri); @Override UserDetails loadUserByUsername(String username); @Override void createUser(UserDetails userDetails); @Override void updateUser(UserDetails userDetails); @Override void deleteUser(String username); @Override void changePassword(String username, String password); @Override boolean userExists(String username); }### Answer:
@Test public void changePassword() throws Exception { server.expect(requestTo("/" + USERNAME)).andExpect(method(PATCH)) .andRespond(withStatus(HttpStatus.OK)); service.changePassword(USERNAME, PASSWORD); server.verify(); } |
### Question:
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(RestTemplateBuilder builder,
@Value("${app.service.url.spanners}") String rootUri); Collection<Spanner> findAll(); Spanner findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }### Answer:
@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)); } |
### Question:
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("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }### Answer:
@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); } |
### Question:
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 findOne(Long id); @PreAuthorize("hasPermission(#spanner, 'owner')") void delete(Spanner spanner); void create(Spanner spanner); @PreAuthorize("hasPermission(#spanner, 'owner')") void update(Spanner spanner); }### Answer:
@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(); } |
### Question:
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("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); }### Answer:
@Test public void findAllTest() throws Exception{ MockUtils.mockGetTest("/mongo/findAll",mockMvc); } |
### Question:
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 String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); }### Answer:
@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 = mvcResult.getResponse().getContentAsString(); System.out.println("更新对象-->" + result); } |
### Question:
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 findOne(@RequestParam String id); @GetMapping("/mongo/findOneByName") Book findOneByName(@RequestParam String name); @PostMapping("/mongo/update") String update(@RequestBody Book book); @PostMapping("/mongo/delOne") String delOne(@RequestBody Book book); @GetMapping("/mongo/delById") String delById(@RequestParam String id); @GetMapping("/mongo/findLikes") List<Book> findByLikes(@RequestParam String search); }### Answer:
@Test public void findByLikesTest() throws Exception{ MockUtils.mockGetTest("/mongo/findLikes?search=从",mockMvc); } |
### Question:
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; i < limit; i++) { int j = i + 1; counter++; if (comparator.compare(array[i], array[j]) > 0) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; swapped = true; lastSwap = i; } } } return counter; } int sort(T[] array, Comparator<T> comparator, boolean optimized); }### Answer:
@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("a", array[0]); assertEquals("b", array[1]); assertEquals("c", array[2]); assertEquals("d", array[3]); }
@Test public void testInverted(){ String[] array = {"d", "c", "b", "a"}; int comparisons = sorter.sort(array, new StringComparator(), false); assertEquals(12, comparisons); assertEquals("a", array[0]); assertEquals("b", array[1]); assertEquals("c", array[2]); assertEquals("d", array[3]); }
@Test public void testBase(){ String[] array = {"d", "a", "c", "b"}; sorter.sort(array, new StringComparator(), false); assertEquals("a", array[0]); assertEquals("b", array[1]); assertEquals("c", array[2]); assertEquals("d", array[3]); }
@Test public void testNearly(){ String[] array = {"c", "b", "a", "d", "e", "f"}; int optimized = sorter.sort(array, new StringComparator(), true); array = new String[]{"c", "b", "a", "d", "e", "f"}; int base = sorter.sort(array, new StringComparator(), false); assertTrue(optimized < base); assertTrue(optimized < base/2); assertEquals("a", array[0]); assertEquals("b", array[1]); assertEquals("c", array[2]); assertEquals("d", array[3]); assertEquals("e", array[4]); assertEquals("f", array[5]); }
@Test public void testGameUsers(){ GameUser a = new GameUser("a", 10); GameUser b = new GameUser("b", 5); GameUser c = new GameUser("c", 2); GameUser d = new GameUser("d", 5); GameUser[] array = {a,b,c,d}; sorter.sort(array, new GameUserComparator(), true); assertEquals("c", array[0].getUserId()); assertEquals("b", array[1].getUserId()); assertEquals("d", array[2].getUserId()); assertEquals("a", array[3].getUserId()); } |
### Question:
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(); }### Answer:
@Test public void testFailToPeekOnEmpty(){ assertThrows(RuntimeException.class, () -> queue.peek()); } |
### Question:
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); }### Answer:
@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[]{"Hi", "first row"}; foo[1] = new String[]{"Hello", "second row", "rows do not have to have same length"}; String[][] copy = CopyExample.copyWrong(foo); checkSameData(foo, copy); String WRONG = "WRONG"; copy[0] = new String[]{WRONG}; assertEquals(2, foo[0].length); assertNotEquals(WRONG, foo[0][0]); assertEquals("Hi", foo[0][0]); copy[1][0] = WRONG; assertEquals(WRONG, foo[1][0]); } |
### Question:
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[][] copyWrong(String[][] input); static String[][] copy(String[][] input); }### Answer:
@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[][] foo = new String[2][]; foo[0] = new String[]{"Hi", "first row"}; foo[1] = new String[]{"Hello", "second row", "raws do not have to have same length"}; String[][] copy = CopyExample.copy(foo); checkSameData(foo, copy); String WRONG = "WRONG"; copy[0] = new String[]{WRONG}; assertEquals(2, foo[0].length); assertNotEquals(WRONG, foo[0][0]); assertEquals("Hi", foo[0][0]); copy[1][0] = WRONG; assertNotEquals(WRONG, foo[1][0]); assertEquals("Hello", foo[1][0]); } |
### Question:
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); }### Answer:
@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", "bar", 0); assertFalse(users.isPresent(copy)); User changedCopy = new User("changed", "bar", 0); assertEquals(foo, changedCopy); assertFalse(users.isPresent(changedCopy)); foo.setName("foo"); assertTrue(users.isPresent(copy)); } |
### Question:
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(); }### Answer:
@Test public void testEmpty() { assertEquals(0, set.size()); assertTrue(set.isEmpty()); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(String x); }### Answer:
@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_00_00_00_00L)); }
@Test public void testHashLongToIntNegative(){ long one32times = 0xFF_FF_FF_FFL; assertTrue(one32times > 2_000_000_000); assertEquals(-1, HashFunctions.hashLongToInt(one32times)); long singleOne = 0x80_00_00_00L; assertTrue(singleOne > 2_000_000_000); int hashed = HashFunctions.hashLongToInt(singleOne); assertTrue(hashed < -2_000_000_000); assertEquals(Integer.MIN_VALUE, hashed); } |
### Question:
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 hashStringSumRevised(String x); }### Answer:
@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_0000_0000_0000L; assertNotEquals(HashFunctions.hashLongToInt(x), HashFunctions.hashLongToInt(w)); assertEquals(HashFunctions.hashLongToInt(x), HashFunctions.hashLongToInt(z)); assertNotEquals(HashFunctions.hashLongToIntRevised(x), HashFunctions.hashLongToIntRevised(w)); assertNotEquals(HashFunctions.hashLongToIntRevised(x), HashFunctions.hashLongToIntRevised(z)); } |
### Question:
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(start); mainLoop: while(! queue.isEmpty()){ V parent = queue.poll(); for(V child : graph.get(parent)){ if( child.equals(start) || bestParent.get(child) != null){ continue; } bestParent.put(child, parent); if(child.equals(end)){ break mainLoop; } queue.add(child); } } if(! bestParent.containsKey(end)){ return null; } List<V> path = new ArrayList<>(); V current = end; while (current != null){ path.add(0, current); current = bestParent.get(current); } return path; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); }### Answer:
@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> graph = createGraph(); List<Integer> path = graph.findPathBFS(2, 8); assertNotNull(path); assertEquals(4, path.size()); assertEquals(2, (int) path.get(0)); assertEquals(3, (int) path.get(1)); assertEquals(6, (int) path.get(2)); assertEquals(8, (int) path.get(3)); }
@Test public void testNoPathBFS(){ Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathBFS(3, 9); assertNull(path); } |
### Question:
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(alreadyVisited, stack, start, end); if(isPathTo(stack, end)){ List<V> path = new ArrayList<>(stack); Collections.reverse(path); return path; } return null; } @Override void addVertex(V vertex); @Override void addEdge(V from, V to); @Override int getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); }### Answer:
@Test public void testNoPathDFS(){ Graph<Integer> graph = createGraph(); List<Integer> path = graph.findPathDFS(10, 4); assertNull(path); } |
### Question:
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 getNumberOfVertices(); @Override int getNumberOfEdges(); @Override void removeEdge(V from, V to); @Override void removeVertex(V vertex); @Override Collection<V> getAdjacents(V vertex); @Override List<V> findPathDFS(V start, V end); @Override List<V> findPathBFS(V start, V end); @Override Set<V> findConnected(V vertex); @Override Set<V> findConnected(Iterable<V> vertices); }### Answer:
@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()); } |
### Question:
GenericExample { public <Z> MyPair<T,Z> createPair(T t, Z z){ MyPair<T, Z> pair = new MyPair<>(t, z); return pair; } Object identityObject(Object x); T identityGeneric(T x); Z identityGenericOnMethod(T t, Z z); MyPair<T,Z> createPair(T t, Z z); Comparable max(Comparable x, Comparable y); Z maxWithGenerics(Z x, Z y); }### Answer:
@Test public void testMultiGenerics(){ GenericExample<String> example = new GenericExample<>(); GenericExample.MyPair<String, Integer> pair = example.createPair("foo", 5); assertNotNull(pair); assertEquals("foo", pair.x); assertEquals((Integer)5, pair.y); GenericExample.MyPair<String, String> other = example.createPair("foo", "bar"); assertNotNull(other); assertEquals("foo", other.x); assertEquals("bar", other.y); } |
### Question:
ArrayExample { public static int sum(int[] array){ if(array == null){ return 0; } int sum = 0; for(int i=0; i< array.length; i++){ sum += array[i]; } return sum; } static int sum(int[] array); }### Answer:
@Test public void testBase(){ int[] array = {1, 2, 3}; int res = ArrayExample.sum(array); assertEquals(6, res); }
@Test public void testNegative(){ int[] array = new int[3]; array[0] = -2; array[1] = -1; int res = ArrayExample.sum(array); assertEquals(-3, res); }
@Test public void testLarge(){ int x = 1_000_000_000; int[] array = {x, x, x}; int res = ArrayExample.sum(array); assertTrue(res < 0); } |
### Question:
GreedyForKnapsack { public static boolean[] solveByHeavierFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff < 0){ return 1; } else if(diff > 0){ return -1; } else { return 0; } }); return solve(problem, items); } static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem); }### Answer:
@Test public void testSolveByHeavierFirst(){ KnapsackInstanceWithSolution p = KnapsackInstanceWithSolution.problemP05(); boolean[] res = GreedyForKnapsack.solveByHeavierFirst(p.getProblem()); double fitness = p.getProblem().evaluate(res); assertEquals(47d, fitness, 0.001); double best = p.getBestFitness(); assertNotEquals(best, fitness); assertTrue(best > fitness); } |
### Question:
GreedyForKnapsack { public static boolean[] solveByLighterFirst(KnapsackProblem problem){ List<KnapsackProblem.Item> items = problem.getCopyOfItems(); items.sort((a,b) -> { double diff = a.getWeight() - b.getWeight(); if(diff > 0){ return 1; } else if(diff < 0){ return -1; } else { return 0; } }); return solve(problem, items); } static boolean[] solveByHeavierFirst(KnapsackProblem problem); static boolean[] solveByLighterFirst(KnapsackProblem problem); static boolean[] solveByBestRatioFirst(KnapsackProblem problem); }### Answer:
@Test public void testSolveByLighterFirst(){ KnapsackInstanceWithSolution p = KnapsackInstanceWithSolution.problemP05(); boolean[] res = GreedyForKnapsack.solveByLighterFirst(p.getProblem()); double fitness = p.getProblem().evaluate(res); assertEquals(44d, fitness, 0.001); double best = p.getBestFitness(); assertNotEquals(best, fitness); assertTrue(best > fitness); } |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 38