method2testcases
stringlengths
118
3.08k
### Question: OntologyTerms { public static <O extends Ontology<?, ?>> Set<TermId> childrenOf(TermId termId, O ontology) { Set<TermId> result = new HashSet<>(); visitChildrenOf(termId, ontology, new TermVisitor<O>() { @Override public boolean visit(O ontology, TermId termId) { result.add(termId); return true; } }); return result; } static void visitChildrenOf(TermId termId, O ontology, TermVisitor<O> termVisitor); static Set<TermId> childrenOf(TermId termId, O ontology); static void visitParentsOf(TermId termId, O ontology, TermVisitor<O> termVisitor); static Set<TermId> parentsOf(TermId termId, O ontology); }### Answer: @Test public void testChildrenOf() { assertEquals( "[ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000004], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000005], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000006], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000007], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000002]]", OntologyTerms.childrenOf(idRootVegetable, ontology).toString()); }
### Question: OntologyTerms { public static <O extends Ontology<?, ?>> void visitParentsOf(TermId termId, O ontology, TermVisitor<O> termVisitor) { BreadthFirstSearch<TermId, ImmutableEdge<TermId>> bfs = new BreadthFirstSearch<>(); @SuppressWarnings("unchecked") DirectedGraph<TermId, ImmutableEdge<TermId>> graph = (DirectedGraph<TermId, ImmutableEdge<TermId>>) ontology.getGraph(); bfs.startFromForward(graph, termId, new VertexVisitor<TermId, ImmutableEdge<TermId>>() { @Override public boolean visit(DirectedGraph<TermId, ImmutableEdge<TermId>> g, TermId v) { return termVisitor.visit(ontology, v); } }); } static void visitChildrenOf(TermId termId, O ontology, TermVisitor<O> termVisitor); static Set<TermId> childrenOf(TermId termId, O ontology); static void visitParentsOf(TermId termId, O ontology, TermVisitor<O> termVisitor); static Set<TermId> parentsOf(TermId termId, O ontology); }### Answer: @Test public void testVisitParentsOf() { Set<TermId> parents = new TreeSet<>(); OntologyTerms.visitParentsOf(idBlueCarrot, ontology, new TermVisitor<ImmutableOntology<VegetableTerm, VegetableTermRelation>>() { @Override public boolean visit(ImmutableOntology<VegetableTerm, VegetableTermRelation> ontology, TermId termId) { parents.add(termId); return true; } }); assertEquals( "[ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000001], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000002], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000004], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000007]]", parents.toString()); }
### Question: OntologyTerms { public static <O extends Ontology<?, ?>> Set<TermId> parentsOf(TermId termId, O ontology) { Set<TermId> result = new HashSet<>(); visitParentsOf(termId, ontology, new TermVisitor<O>() { @Override public boolean visit(O ontology, TermId termId) { result.add(termId); return true; } }); return result; } static void visitChildrenOf(TermId termId, O ontology, TermVisitor<O> termVisitor); static Set<TermId> childrenOf(TermId termId, O ontology); static void visitParentsOf(TermId termId, O ontology, TermVisitor<O> termVisitor); static Set<TermId> parentsOf(TermId termId, O ontology); }### Answer: @Test public void testParentsOf() { assertEquals( "[ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000004], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000007], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000001], ImmutableTermId [prefix=ImmutableTermPrefix [value=VO], id=0000002]]", OntologyTerms.parentsOf(idBlueCarrot, ontology).toString()); }
### Question: ObjectScoreDistribution implements Serializable { public double estimatePValue(double score) { Entry<Double, Double> previous = null; for (Entry<Double, Double> entry : cumulativeFrequencies.entrySet()) { if (previous == null && score < entry.getKey()) { return 1.0; } if (previous != null && previous.getKey() <= score && score < entry.getKey()) { final double dx = (entry.getKey() - previous.getKey()) / 2.0; return 1 - (previous.getValue() + dx * (entry.getValue() - previous.getValue())); } previous = entry; } return 0.0; } ObjectScoreDistribution(int objectId, int numTerms, int sampleSize, SortedMap<Double, Double> cumulativeFrequencies); double estimatePValue(double score); List<Double> observedScores(); SortedMap<Double, Double> getCumulativeFrequencies(); int getObjectId(); int getNumTerms(); int getSampleSize(); @Override String toString(); }### Answer: @Test public void testEstimatePValue() { assertEquals(1.0, objDist.estimatePValue(0.0), 0.01); assertEquals(0.82, objDist.estimatePValue(0.2), 0.01); assertEquals(0.82, objDist.estimatePValue(0.4), 0.01); assertEquals(0.42, objDist.estimatePValue(0.6), 0.01); assertEquals(0.42, objDist.estimatePValue(0.8), 0.01); assertEquals(0.0, objDist.estimatePValue(0.99), 0.01); }
### Question: ScoreDistributions { public static ScoreDistribution merge(Collection<ScoreDistribution> distributions) { if (distributions.isEmpty()) { throw new CannotMergeScoreDistributions("Cannot merge zero ScoreDistributions objects."); } if (distributions.stream().map(d -> d.getNumTerms()).collect(Collectors.toSet()).size() != 1) { throw new CannotMergeScoreDistributions("Different numbers of terms used for precomputation"); } Map<Integer, ObjectScoreDistribution> mapping = new HashMap<>(); for (ScoreDistribution d : distributions) { for (Integer objectId : d.getObjectIds()) { final ObjectScoreDistribution dist = d.getObjectScoreDistribution(objectId); if (mapping.containsKey(objectId)) { throw new CannotMergeScoreDistributions("Duplicate object ID " + objectId + " detected"); } else { mapping.put(objectId, dist); } } } return new ScoreDistribution(distributions.stream().findAny().get().getNumTerms(), mapping); } static ScoreDistribution merge(Collection<ScoreDistribution> distributions); static ScoreDistribution merge(ScoreDistribution... distributions); }### Answer: @Test public void test() { ScoreDistribution result = ScoreDistributions.merge(dist1, dist2); assertEquals(2, result.getNumTerms()); assertEquals("[1, 2]", ImmutableSortedSet.copyOf(result.getObjectIds()).toString()); assertEquals(1, result.getObjectScoreDistribution(1).getObjectId()); assertEquals(2, result.getObjectScoreDistribution(2).getObjectId()); }
### Question: ScoreSamplingOptions implements Serializable, Cloneable { @Override public String toString() { return "ScoreSamplingOptions [numThreads=" + numThreads + ", minObjectId=" + minObjectId + ", maxObjectId=" + maxObjectId + ", minNumTerms=" + minNumTerms + ", maxNumTerms=" + maxNumTerms + ", numIterations=" + numIterations + ", seed=" + seed + "]"; } ScoreSamplingOptions(); ScoreSamplingOptions(int numThreads, Integer minObjectId, Integer maxObjectId, int minNumTerms, int maxNumTerms, int seed, int numIterations); int getNumThreads(); void setNumThreads(int numThreads); Integer getMinObjectId(); void setMinObjectId(Integer minObjectId); Integer getMaxObjectId(); void setMaxObjectId(Integer maxObjectId); int getMinNumTerms(); void setMinNumTerms(int minNumTerms); int getMaxNumTerms(); void setMaxNumTerms(int maxNumTerms); int getSeed(); void setSeed(int seed); int getNumIterations(); void setNumIterations(int numIterations); @Override Object clone(); @Override String toString(); }### Answer: @Test public void testDefaultConstruction() { samplingOptions = new ScoreSamplingOptions(); assertEquals( "ScoreSamplingOptions [numThreads=1, minObjectId=null, maxObjectId=null, minNumTerms=1, maxNumTerms=20, numIterations=100000, seed=42]", samplingOptions.toString()); } @Test public void testFullConstruction() { samplingOptions = new ScoreSamplingOptions(1, 1, 2, 3, 4, 5, 6); assertEquals( "ScoreSamplingOptions [numThreads=1, minObjectId=1, maxObjectId=2, minNumTerms=3, maxNumTerms=4, numIterations=6, seed=5]", samplingOptions.toString()); }
### Question: ImmutableEdge implements Edge<V> { @Override public final Object clone() { return new ImmutableEdge<V>(source, dest, id); } ImmutableEdge(final V source, final V dest, final int id); static ImmutableEdge<V> construct(final V source, final V dest, final int id); @Override final V getSource(); @Override final V getDest(); @Override final int getId(); @Override final Object clone(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(Edge<V> o); }### Answer: @Test @SuppressWarnings("unchecked") public void testClone() { ImmutableEdge<Integer> e2 = (ImmutableEdge<Integer>) edge.clone(); assertNotSame(edge, e2); assertEquals(edge, e2); assertEquals("ImmutableEdge [source=1, dest=2, id=1]", e2.toString()); }
### Question: TermIds { public static Set<TermId> augmentWithAncestors(ImmutableOntology<?, ?> ontology, Set<TermId> termIds, boolean includeRoot) { termIds.addAll(ontology.getAllAncestorTermIds(termIds, includeRoot)); return termIds; } static Set<TermId> augmentWithAncestors(ImmutableOntology<?, ?> ontology, Set<TermId> termIds, boolean includeRoot); }### Answer: @Test public void test() { Set<TermId> inputIds = Sets.newHashSet(id1); Set<TermId> outputIds = ImmutableSortedSet.copyOf(TermIds.augmentWithAncestors(ontology, inputIds, true)); assertEquals( "[ImmutableTermId [prefix=ImmutableTermPrefix [value=HP], id=0000001], ImmutableTermId [prefix=ImmutableTermPrefix [value=HP], id=0000002], ImmutableTermId [prefix=ImmutableTermPrefix [value=HP], id=0000003], ImmutableTermId [prefix=ImmutableTermPrefix [value=HP], id=0000004], ImmutableTermId [prefix=ImmutableTermPrefix [value=HP], id=0000005]]", outputIds.toString()); }
### Question: TermAnnotations { public static Map<TermId, Collection<String>> constructTermAnnotationToLabelsMap( Ontology<?, ?> ontology, Collection<? extends TermAnnotation> annotations) { final Map<TermId, Collection<String>> result = new HashMap<>(); for (TermAnnotation anno : annotations) { for (TermId termId : ontology.getAncestorTermIds(anno.getTermId(), true)) { if (!result.containsKey(termId)) { result.put(termId, Sets.newHashSet(anno.getLabel())); } else { result.get(termId).add(anno.getLabel()); } } } return result; } static Map<TermId, Collection<String>> constructTermAnnotationToLabelsMap( Ontology<?, ?> ontology, Collection<? extends TermAnnotation> annotations); static Map<String, Collection<TermId>> constructTermLabelToAnnotationsMap( Ontology<?, ?> ontology, Collection<? extends TermAnnotation> annotations); }### Answer: @Test public void testConstructTermAnnotationToLabelsMap() { Map<TermId, Collection<String>> map = ImmutableSortedMap .copyOf(TermAnnotations.constructTermAnnotationToLabelsMap(ontology, annotations)); assertEquals( "{ImmutableTermId [prefix=ImmutableTermPrefix [value=HP], id=0000001]=[two, one], ImmutableTermId [prefix=ImmutableTermPrefix [value=HP], id=0000002]=[two, three, one], ImmutableTermId [prefix=ImmutableTermPrefix [value=HP], id=0000003]=[two, one], ImmutableTermId [prefix=ImmutableTermPrefix [value=HP], id=0000004]=[two, one], ImmutableTermId [prefix=ImmutableTermPrefix [value=HP], id=0000005]=[two, three, one]}", map.toString()); }
### Question: ImmutableTermId implements TermId { @Override public int compareTo(TermId that) { return ComparisonChain.start().compare(this.getPrefix(), that.getPrefix()) .compare(this.getId(), that.getId()).result(); } ImmutableTermId(TermPrefix prefix, String id); static ImmutableTermId constructWithPrefix(String termIdString); @Override int compareTo(TermId that); @Override TermPrefix getPrefix(); @Override String getId(); @Override String getIdWithPrefix(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testComparable() { assertEquals(0, termId.compareTo(termId)); assertThat(termId.compareTo(termId2), lessThan(0)); assertThat(termId2.compareTo(termId), greaterThan(0)); }
### Question: ImmutableTermId implements TermId { @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof TermId) { final TermId that = (TermId) obj; return this.prefix.equals(that.getPrefix()) && (this.id.equals(that.getId())); } else { return false; } } ImmutableTermId(TermPrefix prefix, String id); static ImmutableTermId constructWithPrefix(String termIdString); @Override int compareTo(TermId that); @Override TermPrefix getPrefix(); @Override String getId(); @Override String getIdWithPrefix(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testEquals() { assertTrue(termId.equals(termId)); assertFalse(termId.equals(termId2)); }
### Question: ImmutableTermId implements TermId { @Override public String toString() { return "ImmutableTermId [prefix=" + prefix + ", id=" + id + "]"; } ImmutableTermId(TermPrefix prefix, String id); static ImmutableTermId constructWithPrefix(String termIdString); @Override int compareTo(TermId that); @Override TermPrefix getPrefix(); @Override String getId(); @Override String getIdWithPrefix(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testToString() { assertEquals("ImmutableTermId [prefix=ImmutableTermPrefix [value=HP], id=0000001]", termId.toString()); }
### Question: ImmutableTermPrefix implements TermPrefix { @Override public int compareTo(TermPrefix o) { if (this == o) { return 0; } else { return value.compareTo(o.getValue()); } } ImmutableTermPrefix(String value); @Override int compareTo(TermPrefix o); @Override String getValue(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testComparable() { assertEquals(0, termPrefix.compareTo(termPrefix)); assertThat(termPrefix.compareTo(termPrefix2), greaterThan(0)); assertThat(termPrefix2.compareTo(termPrefix), lessThan(0)); }
### Question: ImmutableTermPrefix implements TermPrefix { @Override public String getValue() { return value; } ImmutableTermPrefix(String value); @Override int compareTo(TermPrefix o); @Override String getValue(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testQueryFunctions() { assertEquals("HP", termPrefix.getValue()); }
### Question: ImmutableTermPrefix implements TermPrefix { @Override public String toString() { return "ImmutableTermPrefix [value=" + value + "]"; } ImmutableTermPrefix(String value); @Override int compareTo(TermPrefix o); @Override String getValue(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testToString() { assertEquals("ImmutableTermPrefix [value=HP]", termPrefix.toString()); }
### Question: ImmutableEdge implements Edge<V> { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") ImmutableEdge<V> other = (ImmutableEdge<V>) obj; if (dest == null) { if (other.dest != null) { return false; } } else if (!dest.equals(other.dest)) { return false; } if (id != other.id) { return false; } if (source == null) { if (other.source != null) { return false; } } else if (!source.equals(other.source)) { return false; } return true; } ImmutableEdge(final V source, final V dest, final int id); static ImmutableEdge<V> construct(final V source, final V dest, final int id); @Override final V getSource(); @Override final V getDest(); @Override final int getId(); @Override final Object clone(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(Edge<V> o); }### Answer: @Test @SuppressWarnings("unchecked") public void testEquals() { assertTrue(edge.equals(edge)); ImmutableEdge<Integer> e2 = (ImmutableEdge<Integer>) edge.clone(); assertTrue(edge.equals(e2)); ImmutableEdge<Integer> e3 = ImmutableEdge.construct(3, 2, 1); assertFalse(edge.equals(e3)); ImmutableEdge<Integer> e4 = ImmutableEdge.construct(1, 3, 1); assertFalse(edge.equals(e4)); ImmutableEdge<Integer> e5 = ImmutableEdge.construct(1, 2, 3); assertFalse(edge.equals(e5)); }
### Question: SimpleFeatureVectorSimilarity implements Similarity { @Override public double computeScore(Collection<TermId> query, Collection<TermId> target) { return Sets.intersection(Sets.newHashSet(query), Sets.newHashSet(target)).size(); } @Override String getName(); @Override String getParameters(); @Override boolean isSymmetric(); @Override double computeScore(Collection<TermId> query, Collection<TermId> target); }### Answer: @Test public void testComputeSimilarities() { assertEquals(1.0, similarity.computeScore( Lists.newArrayList(ImmutableTermId.constructWithPrefix("HP:0000008"), ImmutableTermId.constructWithPrefix("HP:0000009")), Lists.newArrayList(ImmutableTermId.constructWithPrefix("HP:0000008"))), 0.01); assertEquals(1.0, similarity.computeScore( Lists.newArrayList(ImmutableTermId.constructWithPrefix("HP:0000008"), ImmutableTermId.constructWithPrefix("HP:0000009")), Lists.newArrayList(ImmutableTermId.constructWithPrefix("HP:0000008"), ImmutableTermId.constructWithPrefix("HP:0000010"))), 0.01); assertEquals(0.0, similarity.computeScore( Lists.newArrayList(ImmutableTermId.constructWithPrefix("HP:0000009")), Lists.newArrayList(ImmutableTermId.constructWithPrefix("HP:0000008"), ImmutableTermId.constructWithPrefix("HP:0000010"))), 0.01); }
### Question: JaccardSimilarity implements Similarity { @Override public double computeScore(Collection<TermId> query, Collection<TermId> target) { final Set<TermId> termIdsQuery = ontology.getAllAncestorTermIds(query, false); final Set<TermId> termIdsTarget = ontology.getAllAncestorTermIds(target, false); double intersectionSize = Sets.intersection(termIdsQuery, termIdsTarget).size(); if (normalized) { return intersectionSize / Sets.union(termIdsQuery, termIdsTarget).size(); } else { return intersectionSize; } } JaccardSimilarity(Ontology<T, R> ontology); JaccardSimilarity(Ontology<T, R> ontology, boolean normalized); @Override String getName(); @Override String getParameters(); @Override boolean isSymmetric(); @Override double computeScore(Collection<TermId> query, Collection<TermId> target); }### Answer: @Test public void testComputeSimilarities() { assertEquals(0.25, similarity.computeScore(Lists.newArrayList(idBeet), Lists.newArrayList(idCarrot)), 0.01); assertEquals(0.66, similarity.computeScore(Lists.newArrayList(idBlueCarrot), Lists.newArrayList(idCarrot)), 0.01); assertEquals(0.33, similarity.computeScore(Lists.newArrayList(idPumpkin), Lists.newArrayList(idCarrot)), 0.01); assertEquals(0.0, similarity.computeScore(Lists.newArrayList(idLeafVegetable), Lists.newArrayList(idCarrot)), 0.01); }
### Question: CosineSimilarity implements Similarity { @Override public double computeScore(Collection<TermId> query, Collection<TermId> target) { final Set<TermId> termIdsQuery = ontology.getAllAncestorTermIds(query, false); final Set<TermId> termIdsTarget = ontology.getAllAncestorTermIds(target, false); return Sets.intersection(termIdsQuery, termIdsTarget).size() / (Math.sqrt(termIdsQuery.size()) * Math.sqrt(termIdsTarget.size())); } CosineSimilarity(Ontology<T, R> ontology); CosineSimilarity(Ontology<T, R> ontology, boolean oppositeAware); @Override String getName(); @Override String getParameters(); @Override boolean isSymmetric(); @Override double computeScore(Collection<TermId> query, Collection<TermId> target); }### Answer: @Test public void testComputeSimilarities() { assertEquals(0.408, similarity.computeScore(Lists.newArrayList(idBeet), Lists.newArrayList(idCarrot)), 0.01); assertEquals(0.816, similarity.computeScore(Lists.newArrayList(idBlueCarrot), Lists.newArrayList(idCarrot)), 0.01); assertEquals(0.50, similarity.computeScore(Lists.newArrayList(idPumpkin), Lists.newArrayList(idCarrot)), 0.01); assertEquals(0.0, similarity.computeScore(Lists.newArrayList(idLeafVegetable), Lists.newArrayList(idCarrot)), 0.01); }
### Question: PrecomputingPairwiseResnikSimilarity implements PairwiseSimilarity, Serializable { @Override public double computeScore(TermId query, TermId target) { return precomputedScores.get(query, target); } PrecomputingPairwiseResnikSimilarity(Ontology<T, R> ontology, Map<TermId, Double> termToIc, int numThreads); PrecomputingPairwiseResnikSimilarity(Ontology<T, R> ontology, Map<TermId, Double> termToIc); @Override double computeScore(TermId query, TermId target); }### Answer: @Test public void testComputeSimilarities() { assertEquals(0.0, similarity.computeScore(idBeet, idCarrot), 0.01); assertEquals(0.405, similarity.computeScore(idBlueCarrot, idCarrot), 0.01); assertEquals(0.0, similarity.computeScore(idPumpkin, idCarrot), 0.01); assertEquals(0.0, similarity.computeScore(idLeafVegetable, idCarrot), 0.01); }
### Question: TermOverlapSimilarity implements Similarity { @Override public double computeScore(Collection<TermId> query, Collection<TermId> target) { final Set<TermId> termIdsQuery = ontology.getAllAncestorTermIds(query, false); final Set<TermId> termIdsTarget = ontology.getAllAncestorTermIds(target, false); double overlap = Sets.intersection(termIdsQuery, termIdsTarget).size(); if (!normalized) { return overlap; } else { return overlap / Math.min(termIdsQuery.size(), termIdsTarget.size()); } } TermOverlapSimilarity(Ontology<T, R> ontology); TermOverlapSimilarity(Ontology<T, R> ontology, boolean normalized); @Override String getName(); @Override String getParameters(); @Override boolean isSymmetric(); @Override double computeScore(Collection<TermId> query, Collection<TermId> target); }### Answer: @Test public void testComputeSimilarities() { assertEquals(0.5, similarity.computeScore(Lists.newArrayList(idBeet), Lists.newArrayList(idCarrot)), 0.01); assertEquals(1.0, similarity.computeScore(Lists.newArrayList(idBlueCarrot), Lists.newArrayList(idCarrot)), 0.01); assertEquals(0.5, similarity.computeScore(Lists.newArrayList(idPumpkin), Lists.newArrayList(idCarrot)), 0.01); assertEquals(0.0, similarity.computeScore(Lists.newArrayList(idLeafVegetable), Lists.newArrayList(idCarrot)), 0.01); }
### Question: PairwiseResnikSimilarity implements PairwiseSimilarity { @Override public double computeScore(TermId query, TermId target) { return computeScoreImpl(query, target); } protected PairwiseResnikSimilarity(); PairwiseResnikSimilarity(Ontology<T, R> ontology, Map<TermId, Double> termToIc); double computeScoreImpl(TermId query, TermId target); @Override double computeScore(TermId query, TermId target); Ontology<T, R> getOntology(); Map<TermId, Double> getTermToIc(); }### Answer: @Test public void testComputeSimilarities() { assertEquals(0.0, similarity.computeScore(idBeet, idCarrot), 0.01); assertEquals(0.405, similarity.computeScore(idBlueCarrot, idCarrot), 0.01); assertEquals(0.0, similarity.computeScore(idPumpkin, idCarrot), 0.01); assertEquals(0.0, similarity.computeScore(idLeafVegetable, idCarrot), 0.01); }
### Question: ResnikSimilarity extends AbstractCommonAncestorSimilarity<T, R> { @Override public String getName() { return "Resnik similarity"; } ResnikSimilarity(Ontology<T, R> ontology, Map<TermId, Double> termToIc, boolean symmetric); ResnikSimilarity(PairwiseSimilarity pairwiseSimilarity, boolean symmetric); @Override String getName(); }### Answer: @Test public void testQueries() { assertEquals("Resnik similarity", similarity.getName()); assertEquals(true, similarity.isSymmetric()); assertEquals("{symmetric: true}", similarity.getParameters()); }
### Question: BronWatchList { public boolean isWatched(Entiteit entity) { return list.containsKey(Hibernate.getClass(entity)); } boolean isWatched(Entiteit entity); boolean isWatched(Entiteit entiteit, String property); static boolean isSleutelWaarde(Entiteit entiteit, String expression); static boolean isSleutelWaarde(IdObject entity, String propertyName); }### Answer: @Test public void controleerDeelnemerProperties() { Deelnemer deelnemer = new Deelnemer(); assertTrue(watches.isWatched(deelnemer)); assertTrue(watches.isWatched(deelnemer, "onderwijsnummer")); assertFalse(watches.isWatched(deelnemer, "id")); } @Test public void controleerPersoonProperties() { Persoon persoon = new Persoon(); assertTrue(watches.isWatched(persoon)); assertTrue(watches.isWatched(persoon, "bsn")); assertTrue(watches.isWatched(persoon, "officieleAchternaam")); assertFalse(watches.isWatched(persoon, "id")); }
### Question: ResourceUtil { public static void flush(Object objectToFlush) { if (objectToFlush instanceof Flushable) { Flushable flushable = (Flushable) objectToFlush; try { flushable.flush(); } catch (IOException e) { log.error(e.toString(), e); throw new RuntimeException(e); } } } private ResourceUtil(); static void closeQuietly(Closeable closeable); static void closeQuietly(ResultSet closeable); static void closeQuietly(Statement closeable); static void closeQuietly(Connection closeable); static void rollbackQuietly(Connection connection); static String readClasspathFile(Class< ? > clazz, String filename); static String readClasspathFile(Class< ? > clazz, String filename, String charset); static byte[] readClassPathFileAsBytes(Class< ? > clazz, String filename); static int copy(final InputStream in, final OutputStream out); static void flush(Object objectToFlush); }### Answer: @Test(expected = RuntimeException.class) public void flushWithException() { ResourceUtil.flush(new Flushable() { @Override public void flush() throws IOException { throw new IOException("Een verwachte exceptie"); } }); } @Test public void flushWithNull() { ResourceUtil.flush(null); } @Test public void flush() { ResourceUtil.flush(new Flushable() { @Override public void flush() { flushed = true; } }); Assert.assertTrue(flushed); }
### Question: Utf8BufferedWriter extends BufferedWriter { public void writeByteOrderMark() throws IOException { write(new String(BOM, "UTF-8")); } Utf8BufferedWriter(File file); Utf8BufferedWriter(File file, int size); void writeByteOrderMark(); static byte[] BOM; }### Answer: @Test public void testWriteByteOrderMark() throws IOException { String filename = "target/Utf8BufferedWriterTest_bom.txt"; String text = "UTF-8 Test met byte order mark"; writeString(createWriter(filename), true, text); FileInputStream in = new FileInputStream(filename); byte[] actual = new byte[3]; in.read(actual, 0, 3); byte[] actualText = new byte[text.length()]; in.read(actualText); in.close(); Assert.assertArrayEquals(Utf8BufferedWriter.BOM, actual); Assert.assertArrayEquals(text.getBytes(), actualText); }
### Question: BronStateChange implements Serializable { @Override public String toString() { return entity.getClass().getSimpleName() + "." + propertyName + ": " + toString(previousValue) + " -> " + toString(currentValue); } BronStateChange(IdObject entity, String propertyName, Object previousValue, Object currentValue); boolean isSleutelwaardeWijziging(); IdObject getEntity(); String getPropertyName(); @SuppressWarnings("unchecked") T getPreviousValue(); @SuppressWarnings("unchecked") T getCurrentValue(); @Override String toString(); }### Answer: @Test public void nieuweWaarde() { BronStateChange change = new BronStateChange(new Deelnemer(), "naam", null, "Alexander"); assertThat(change.toString(), is("Deelnemer.naam: -> Alexander")); } @Test public void datumWaarde() { Persoon persoon = new Persoon(); persoon.setId(12345L); BronStateChange change = new BronStateChange(persoon, "geboorteDatum", TimeUtil.getInstance().parseDateString( "2009-01-01"), null); assertThat(change.toString(), is("Persoon.geboorteDatum: 2009-01-01 -> ")); }
### Question: Token extends InstellingEntiteit { public String getSerienummer() { return serienummer; } Token(String serienummer, String applicatie, String blob); protected Token(); boolean verifieerPassword(String password); @SuppressWarnings("hiding") void geefUit(Account gebruiker); void neemIn(); void meldDefect(); void repareer(); void blokkeer(); void deblokkeer(); TokenStatus getStatus(); Account getGebruiker(); String getVascoSerienummer(); String getSerienummer(); }### Answer: @Test public void applicatienaamWordtVerwijderdVanSerienummer() { assertThat(token.getSerienummer(), is("123456789")); } @Test public void serienummerZonderapplicatienaamBlijftSerienummer() { assertThat(token.getSerienummer(), is("123456789")); }
### Question: Token extends InstellingEntiteit { public TokenStatus getStatus() { return status; } Token(String serienummer, String applicatie, String blob); protected Token(); boolean verifieerPassword(String password); @SuppressWarnings("hiding") void geefUit(Account gebruiker); void neemIn(); void meldDefect(); void repareer(); void blokkeer(); void deblokkeer(); TokenStatus getStatus(); Account getGebruiker(); String getVascoSerienummer(); String getSerienummer(); }### Answer: @Test public void standaardStatusIsBeschikbaar() { assertThat(token.getStatus(), is(Beschikbaar)); }
### Question: BronWatchList { public static boolean isSleutelWaarde(Entiteit entiteit, String expression) { Class< ? > key = Hibernate.getClass(entiteit); HashMap<String, Property> properties = list.get(key); if (properties != null && properties.containsKey(expression)) { Property property = properties.get(expression); return property.isSleutelGegeven(); } return false; } boolean isWatched(Entiteit entity); boolean isWatched(Entiteit entiteit, String property); static boolean isSleutelWaarde(Entiteit entiteit, String expression); static boolean isSleutelWaarde(IdObject entity, String propertyName); }### Answer: @Test public void isSleutelgegeven() { assertTrue(BronWatchList.isSleutelWaarde(new Persoon(), "bsn")); assertTrue(BronWatchList.isSleutelWaarde(new Deelnemer(), "onderwijsnummer")); assertFalse(BronWatchList.isSleutelWaarde(new Deelnemer(), "indicatieGehandicapt")); assertFalse(BronWatchList.isSleutelWaarde(new Deelnemer(), "xxx")); assertFalse(BronWatchList.isSleutelWaarde(new Deelnemer(), "")); assertFalse(BronWatchList.isSleutelWaarde(new Deelnemer(), null)); }
### Question: Brin extends ExterneOrganisatie { public Brin() { } Brin(); Brin(String brincode); @Exportable String getCode(); void setCode(String brincode); static boolean testBrincode(String brincode); @Override String toString(); void setOnderwijssector(Onderwijssector onderwijssector); Onderwijssector getOnderwijssector(); @Exportable Integer getVestigingsVolgnummer(); static Brin get(String code); static final String BRIN_FORMAT; }### Answer: @Test public void testBrin() { assertThat(Brin.testBrincode("00AA"), is(true)); assertThat(Brin.testBrincode("00AA1"), is(true)); assertThat(Brin.testBrincode("00AA01"), is(true)); assertThat(Brin.testBrincode("0011"), is(true)); assertThat(Brin.testBrincode("00110"), is(true)); assertThat(Brin.testBrincode("001101"), is(true)); assertThat(Brin.testBrincode("0"), is(false)); assertThat(Brin.testBrincode("00"), is(false)); assertThat(Brin.testBrincode("000"), is(false)); assertThat(Brin.testBrincode("AA00"), is(false)); assertThat(Brin.testBrincode("AA00A"), is(false)); assertThat(Brin.testBrincode("0000AA"), is(false)); assertThat(Brin.testBrincode("00AAAA"), is(false)); }
### Question: Brin extends ExterneOrganisatie { @Exportable public Integer getVestigingsVolgnummer() { String brincode = getCode(); if (brincode != null) { Matcher matcher = BRIN_REGEXP.matcher(brincode); if (!matcher.matches()) { Asserts.fail(brincode + " is geen geldige BRIN code"); } String volgnummer = matcher.group(2); if (volgnummer != null) { return Integer.parseInt(volgnummer); } } return null; } Brin(); Brin(String brincode); @Exportable String getCode(); void setCode(String brincode); static boolean testBrincode(String brincode); @Override String toString(); void setOnderwijssector(Onderwijssector onderwijssector); Onderwijssector getOnderwijssector(); @Exportable Integer getVestigingsVolgnummer(); static Brin get(String code); static final String BRIN_FORMAT; }### Answer: @Test public void vestigingVolgnummer() { assertThat(new Brin("00AA1").getVestigingsVolgnummer(), is(1)); assertThat(new Brin("00AA01").getVestigingsVolgnummer(), is(1)); assertThat(new Brin("00AA09").getVestigingsVolgnummer(), is(9)); assertNull(new Brin("00AA").getVestigingsVolgnummer()); }
### Question: Asserts { public static void assertNotNull(final String parameter, final Object waarde) { if (log.isDebugEnabled()) { String waardeText = String.valueOf(waarde); waardeText = waardeText.substring(0, Math.min(waardeText.length(), 16)); log.debug("Controleer dat " + parameter + " niet null is, huidige waarde: '" + waardeText + "'"); } if (waarde == null) { IllegalArgumentException exception = new IllegalArgumentException("Parameter " + parameter + " is null"); throw exception; } } static void assertNotNull(final String parameter, final Object waarde); static void assertNull(final String parameter, final Object waarde); static void assertMaxLength(String parameter, String waarde, int length); static void assertGreaterThanZero(final String parameter, long waarde); static void assertGreaterThanZero(final String parameter, int waarde); static void assertNotEmpty(String parameter, Object waarde); static void assertNotEmpty(String parameter, Collection< ? > list); static void assertEmptyCollection(String parameter, Collection< ? > list); static void assertEquals(String parameter, Object actual, Object expected); static void assertMatchesRegExp(String parameter, String value, String regexp); static void fail(String message); static void assertTrue(String message, boolean conditie); static void assertFalse(String message, boolean conditie); }### Answer: @Test(expected = IllegalArgumentException.class) public void testAssertNotNullMetNull() { Asserts.assertNotNull("foo", null); } @Test public void testAssertNotNullMetNotNull() { Asserts.assertNotNull("foo", new Object()); }
### Question: Asserts { public static void assertNotEmpty(String parameter, Object waarde) { assertNotNull(parameter, waarde); if ("".equals(waarde.toString().trim())) { String bericht = "Parameter " + parameter + " is leeg"; throw new IllegalArgumentException(bericht); } } static void assertNotNull(final String parameter, final Object waarde); static void assertNull(final String parameter, final Object waarde); static void assertMaxLength(String parameter, String waarde, int length); static void assertGreaterThanZero(final String parameter, long waarde); static void assertGreaterThanZero(final String parameter, int waarde); static void assertNotEmpty(String parameter, Object waarde); static void assertNotEmpty(String parameter, Collection< ? > list); static void assertEmptyCollection(String parameter, Collection< ? > list); static void assertEquals(String parameter, Object actual, Object expected); static void assertMatchesRegExp(String parameter, String value, String regexp); static void fail(String message); static void assertTrue(String message, boolean conditie); static void assertFalse(String message, boolean conditie); }### Answer: @Test(expected = IllegalArgumentException.class) public void testAssertNotEmptyMetEmpty() { Asserts.assertNotEmpty("foo", ""); } @Test public void testAssertNotEmptyMetNotEmpty() { Asserts.assertNotEmpty("foo", "123"); }
### Question: SpringBootExample implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(SpringBootExample.class, args); } static void main(String[] args); @Override void run(String... args); }### Answer: @Test public void shouldExecuteMainWithoutExceptions() { SpringBootExample.main(new String[0]); }
### Question: WritableMapConfigurationSource extends MapConfigurationSource implements WritableConfigurationSource { @Override public OptionalValue<String> removeValue(String key, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); return source.containsKey(key) ? present(source.remove(key)) : absent(); } WritableMapConfigurationSource(Map<String, String> source); @Override void setValue(String key, String value, Map<String, String> attributes); @Override OptionalValue<String> removeValue(String key, Map<String, String> attributes); }### Answer: @Test public void shouldRemoveValue() { Map<String, String> map = new HashMap<>(); map.put("key", "value"); WritableConfigurationSource mapConfigurationSource = new WritableMapConfigurationSource(map); mapConfigurationSource.removeValue("key", null); assertThat(mapConfigurationSource.getValue("key", null).isPresent()).isFalse(); }
### Question: PropertiesConfigurationSource implements IterableConfigurationSource { @Override public Iterable<ConfigurationEntry> getAllConfigurationEntries() { Map<String, String> map = source.entrySet().stream() .filter(e -> e.getValue() instanceof String) .collect(toMap(Object::toString, e -> (String) e.getValue())); return new MapIterable(map); } PropertiesConfigurationSource(Properties source); PropertiesConfigurationSource(String propertyFile); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override Iterable<ConfigurationEntry> getAllConfigurationEntries(); }### Answer: @Test public void shouldLoadPropertiesFromFile() { PropertiesConfigurationSource source = new PropertiesConfigurationSource(file.getAbsolutePath()); assertThat(source.getAllConfigurationEntries().iterator()).isEmpty(); }
### Question: PatternConverter implements TypeConverter<Pattern> { @Override public Pattern fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); try { return (value == null) ? null : Pattern.compile(value); } catch (PatternSyntaxException e) { throw new IllegalArgumentException("Unable to convert to a Pattern: " + value, e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Pattern fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Pattern value, Map<String, String> attributes); }### Answer: @Test public void shouldConvertFromString() { Pattern pattern = Pattern.compile(".*"); Pattern value = converter.fromString(Pattern.class, ".*", null); assertThat(value.pattern()).isEqualTo(pattern.pattern()); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValue() { String value = "{"; assertThatThrownBy(() -> converter.fromString(Pattern.class, value, null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert to a Pattern:"); }
### Question: PatternConverter implements TypeConverter<Pattern> { @Override public String toString(Type type, Pattern value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return Objects.toString(value, null); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Pattern fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Pattern value, Map<String, String> attributes); }### Answer: @Test public void shouldConvertToString() { Pattern pattern = Pattern.compile("123.*"); String asString = converter.toString(Pattern.class, pattern, null); assertThat(asString).isEqualTo(pattern.toString()); }
### Question: PatternConverter implements TypeConverter<Pattern> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Pattern.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Pattern fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Pattern value, Map<String, String> attributes); }### Answer: @Test public void shouldAcceptType() { Type type = Pattern.class; boolean isApplicable = converter.isApplicable(type, null); assertThat(isApplicable).isTrue(); } @Test public void shouldNotAcceptUnknownType() { boolean isApplicable = converter.isApplicable(mock(Type.class), null); assertThat(isApplicable).isFalse(); }
### Question: ObjectBuilder { ObjectBuilder beginList() { return beginList(new ArrayList<>()); } }### Answer: @Test public void shouldFailInCaseEndingObjectWhenArrayWasBegun() { assertThatThrowExceptionOfType( new ObjectBuilder().beginList()::endMap, IllegalStateException.class); }
### Question: ObjectBuilder { ObjectBuilder beginMap() { return beginMap(new LinkedHashMap<>()); } }### Answer: @Test public void shouldFailInCaseEndingArrayWhenObjectWasBegun() { assertThatThrowExceptionOfType( new ObjectBuilder().beginMap()::endList, IllegalStateException.class); }
### Question: TypeConverterUtils { static int notEscapedIndexOf(CharSequence value, int startPos, char character) { Objects.requireNonNull(value, "value must not be null"); char prev = 0xffff; for (int i = max(startPos, 0), len = value.length(); i < len; i++) { char current = value.charAt(i); if (current == character) { if (prev == ESCAPE_CHAR) { int m = 1; int l = i - 2; while (l >= 0 && value.charAt(l) == ESCAPE_CHAR) { l--; m++; } if (m % 2 == 0) { return i; } } else { return i; } } prev = current; } return NOT_FOUND; } private TypeConverterUtils(); }### Answer: @Test public void shouldProperlyReturnNotEscapedIndexOf() { assertThat(TypeConverterUtils.notEscapedIndexOf("abcb", 0, 'b')).isEqualTo(1); assertThat(TypeConverterUtils.notEscapedIndexOf("a\\bcb", 0, 'b')).isEqualTo(4); assertThat(TypeConverterUtils.notEscapedIndexOf("a\\b\\\\bcb", 0, 'b')).isEqualTo(5); } @Test public void shouldProperlyReturnNotEscapedIndexOfMultiArgs() { assertThat(TypeConverterUtils.notEscapedIndexOf("abcb", 0, 'b', 'a')).isEqualTo(0); assertThat(TypeConverterUtils.notEscapedIndexOf("a\\bcb", 0, 'b', 'c')).isEqualTo(3); assertThat(TypeConverterUtils.notEscapedIndexOf("a\\b\\\\cb", 0, 'b', 'c')).isEqualTo(5); }
### Question: PeriodConverter implements TypeConverter<Period> { @Override public Period fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); try { return value == null ? null : Period.parse(value); } catch (DateTimeParseException e) { throw new IllegalArgumentException(format("Unable to convert to a Period: %s", value), e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Period fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Period value, Map<String, String> attributes); }### Answer: @Test public void shouldConvertFromString() { Period period = Period.ofDays(123); Period readPeriod = converter.fromString(Period.class, "P123D", null); assertThat(readPeriod).isEqualTo(period); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValue() { String toConvert = "XXXXX"; assertThatThrownBy(() -> converter.fromString(Period.class, toConvert, null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to convert to a Period: XXXXX"); }
### Question: PeriodConverter implements TypeConverter<Period> { @Override public String toString(Type type, Period value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return Objects.toString(value, null); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Period fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Period value, Map<String, String> attributes); }### Answer: @Test public void shouldConvertToString() { Period period = Period.ofDays(123); String asString = converter.toString(Period.class, period, null); assertThat(asString).isEqualTo("P123D"); }
### Question: PeriodConverter implements TypeConverter<Period> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Period.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Period fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Period value, Map<String, String> attributes); }### Answer: @Test public void shouldAcceptPeriodType() { Type type = Period.class; boolean isApplicable = converter.isApplicable(type, null); assertThat(isApplicable).isTrue(); } @Test public void shouldNotAcceptUnknownType() { boolean isApplicable = converter.isApplicable(mock(Type.class), null); assertThat(isApplicable).isFalse(); }
### Question: LongConverter extends AbstractNumberConverter<Long> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Long.class, Long.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableWhenLongType() { Type type = Long.class; boolean applicable = longTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotLongType() { Type type = Boolean.class; boolean applicable = longTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> longTypeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: OffsetDateTimeConverter extends AbstractTemporalAccessorConverter<OffsetDateTime> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && OffsetDateTime.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableWhenOffsetDateTimeType() { Type type = OffsetDateTime.class; boolean applicable = offsetDateTimeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotOffsetDateTimeType() { Type type = Boolean.class; boolean applicable = offsetDateTimeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> offsetDateTimeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: CharacterConverter implements TypeConverter<Character> { @Override public String toString(Type type, Character value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : escapeJava(value.toString()); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Character fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Character value, Map<String, String> attributes); }### Answer: @Test public void shouldWriteValueAsString() { Character value = 'A'; String asString = converter.toString(Character.class, value, null); assertThat(asString).isEqualTo("A"); } @Test public void shouldConvertToNullFromNull() { Character value = null; String asString = converter.toString(Character.class, value, null); assertThat(asString).isNull(); } @Test public void shouldUnescapeEscapedString() { Character value = '\u0080'; String asString = converter.toString(Character.class, value, null); assertThat(asString).isEqualTo("\\u0080"); }
### Question: CharacterConverter implements TypeConverter<Character> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && (Character.class.isAssignableFrom((Class<?>) type) || Character.TYPE.isAssignableFrom((Class<?>) type)); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Character fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Character value, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableToCharacter() { boolean applicable = converter.isApplicable(Character.class, null); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableToNonCharacter() { boolean applicable = converter.isApplicable(Object.class, null); assertThat(applicable).isFalse(); }
### Question: DurationConverter implements TypeConverter<Duration> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Duration.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Duration fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Duration value, Map<String, String> attributes); static final String FORMAT; }### Answer: @Test public void shouldAcceptReadableDurationType() { Type type = Duration.class; boolean isApplicable = converter.isApplicable(type, null); assertThat(isApplicable).isTrue(); } @Test public void shouldNotAcceptUnknownType() { boolean isApplicable = converter.isApplicable(mock(Type.class), null); assertThat(isApplicable).isFalse(); }
### Question: ByteConverter extends AbstractNumberConverter<Byte> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Byte.class, Byte.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableWhenByteType() { Type type = Byte.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotByteType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: LocalDateTimeConverter extends AbstractTemporalAccessorConverter<LocalDateTime> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && LocalDateTime.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableWhenLocalDateTimeType() { Type type = LocalDateTime.class; boolean applicable = localDateTimeTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotLocalDateTimeType() { Type type = Boolean.class; boolean applicable = localDateTimeTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> localDateTimeTypeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: BigDecimalConverter extends AbstractNumberConverter<BigDecimal> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, BigDecimal.class, null); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableToBigDecimal() { boolean applicable = converter.isApplicable(BigDecimal.class, null); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableToNonBigDecimal() { boolean applicable = converter.isApplicable(Object.class, null); assertThat(applicable).isFalse(); }
### Question: IntegerConverter extends AbstractNumberConverter<Integer> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Integer.class, Integer.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableWhenIntegerType() { Type type = Integer.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotIntegerType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: DoubleConverter extends AbstractNumberConverter<Double> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Double.class, Double.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableWhenDoubleType() { Type type = Double.class; boolean applicable = doubleTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotDoubleType() { Type type = Boolean.class; boolean applicable = doubleTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> doubleTypeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: CurrencyConverter implements TypeConverter<Currency> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Currency.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Currency fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Currency value, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableWhenCurrencyType() { Type type = Currency.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotCurrencyType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenIsApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: YamlConverter implements TypeConverter<T> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); String converter = (attributes == null) ? null : attributes.get(CONVERTER); return ignoreConverterAttribute || Objects.equals(converter, YAML); } YamlConverter(); YamlConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer: @Test void shouldThrowExceptionWhenTypeIsNullAndIsApplicable() { assertThatThrownBy(() -> typeConverter.isApplicable(null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: CurrencyConverter implements TypeConverter<Currency> { @Override public String toString(Type type, Currency value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : value.getCurrencyCode(); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Currency fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Currency value, Map<String, String> attributes); }### Answer: @Test public void shouldConvertToString() { Currency toConvert = Currency.getInstance("USD"); String converted = converter.toString(Currency.class, toConvert, emptyMap()); assertThat(converted).isEqualTo("USD"); } @Test public void shouldReturnNullWhenToStringAndValueIsNull() { String converted = converter.toString(Currency.class, null, emptyMap()); assertThat(converted).isNull(); } @Test public void shouldThrowExceptionWhenToStringAndTypeIsNull() { Currency toConvert = Currency.getInstance("USD"); assertThatThrownBy(() -> converter.toString(null, toConvert, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: CurrencyConverter implements TypeConverter<Currency> { @Override public Currency fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : Currency.getInstance(value); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Currency fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Currency value, Map<String, String> attributes); }### Answer: @Test public void shouldConvertFromString() { String toConvert = "USD"; Currency converted = converter.fromString(Currency.class, toConvert, emptyMap()); assertThat(converted).isEqualTo(Currency.getInstance("USD")); } @Test public void shouldThrowExceptionWhenInvalidFormat() { String toConvert = "invalid"; assertThatThrownBy(() -> converter.fromString(Currency.class, toConvert, emptyMap())) .isExactlyInstanceOf(IllegalArgumentException.class); } @Test public void shouldReturnNullWhenFromStringAndValueIsNull() { Currency converted = converter.fromString(Currency.class, null, emptyMap()); assertThat(converted).isNull(); } @Test public void shouldThrowExceptionWhenFromStringAndTypeIsNull() { String toConvert = "USD"; assertThatThrownBy(() -> converter.fromString(null, toConvert, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: BooleanConverter implements TypeConverter<Boolean> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && (Boolean.class.isAssignableFrom((Class<?>) type) || Boolean.TYPE.isAssignableFrom((Class<?>) type)); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Boolean fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Boolean value, Map<String, String> attributes); static final String FORMAT; }### Answer: @Test public void shouldBeApplicableWhenBooleanType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotBooleanType() { Type type = Integer.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: InstantConverter extends AbstractTemporalAccessorConverter<Instant> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Instant.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String toString(Type type, Instant value, Map<String, String> attributes); static final String ZONE; }### Answer: @Test public void shouldBeApplicableWhenInstantType() { Type type = Instant.class; boolean applicable = instantConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotInstantType() { Type type = Boolean.class; boolean applicable = instantConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> instantConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: StringConverter implements TypeConverter<String> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && String.class.isAssignableFrom((Class<?>) type); } StringConverter(boolean escape); StringConverter(); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, String value, Map<String, String> attributes); static final String ESCAPE; }### Answer: @Test public void shouldBeApplicableWhenStringType() { Type type = String.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotStringType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); }
### Question: StringConverter implements TypeConverter<String> { @Override public String fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return shouldEscape(attributes) ? unescapeJava(value) : value; } StringConverter(boolean escape); StringConverter(); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, String value, Map<String, String> attributes); static final String ESCAPE; }### Answer: @Test public void shouldConvertFromStringWhenFormatNotSpecified() { String in = "One\\\\Two"; String expected = "One\\Two"; String out = converter.fromString(String.class, in, null); assertThat(out).isEqualTo(expected); } @Test public void shouldConvertFromStringWhenFormatSpecifiedAndFalse() { String in = "One\\\\Two"; String escape = "false"; Map<String, String> attributes = singletonMap("escape", escape); String out = converter.fromString(String.class, in, attributes); assertThat(out).isEqualTo(in); } @Test public void shouldConvertFromStringWhenFormatSpecifiedAndTrue() { String in = "One\\\\Two"; String escape = "true"; Map<String, String> attributes = singletonMap("escape", escape); String out = converter.fromString(String.class, in, attributes); assertThat(out).isEqualTo("One\\Two"); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongEscapeValue() { String in = "One\\Two"; String escape = "wrong value"; Map<String, String> attributes = singletonMap("escape", escape); assertThatThrownBy(() -> converter.fromString(String.class, in, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageEndingWith("Invalid 'escape' meta-attribute value, it must be either 'true' or 'false', but 'wrong value' is provided."); }
### Question: GenericsExample { public static void main(String[] args) { new GenericsExample().run(); } static void main(String[] args); }### Answer: @Test public void shouldExecuteMainWithoutExceptions() { GenericsExample.main(new String[0]); }
### Question: StringConverter implements TypeConverter<String> { @Override public String toString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return shouldEscape(attributes) ? escapeJava(value) : value; } StringConverter(boolean escape); StringConverter(); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override String fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, String value, Map<String, String> attributes); static final String ESCAPE; }### Answer: @Test public void shouldConvertToStringWhenFormatNotSpecified() { String in = "One\\Two"; String expected = "One\\\\Two"; String out = converter.toString(String.class, in, null); assertThat(out).isEqualTo(expected); } @Test public void shouldConvertToStringWhenFormatSpecifiedAndFalse() { String in = "One\\Two"; String escape = "false"; Map<String, String> attributes = singletonMap(ESCAPE, escape); String out = converter.toString(String.class, in, attributes); assertThat(out).isEqualTo(in); } @Test public void shouldConvertToStringWhenFormatSpecifiedAndTrue() { String in = "One\\Two"; String escape = "true"; Map<String, String> attributes = singletonMap(ESCAPE, escape); String out = converter.toString(String.class, in, attributes); assertThat(out).isEqualTo("One\\\\Two"); } @Test public void shouldThrowExceptionWhenConvertingToStringAndWrongEscapeValue() { String in = "One\\Two"; String escape = "wrong value"; Map<String, String> attributes = singletonMap(ESCAPE, escape); assertThatThrownBy(() -> converter.toString(String.class, in, attributes)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageEndingWith("Invalid 'escape' meta-attribute value, it must be either 'true' or 'false', but 'wrong value' is provided."); }
### Question: ChainedTypeConverter implements TypeConverter<Object> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return converterFor(type, attributes, false) != null; } ChainedTypeConverter(List<TypeConverter<?>> converters); ChainedTypeConverter(TypeConverter<?>... converters); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Object fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Object value, Map<String, String> attributes); }### Answer: @Test public void shouldSupportConvertersFromTheChain() { TypeConverter<?> converter = new ChainedTypeConverter(new StringConverter(false), new IntegerConverter()); assertThat(converter.isApplicable(String.class, null)).isTrue(); assertThat(converter.isApplicable(Integer.class, null)).isTrue(); assertThat(converter.isApplicable(Long.class, null)).isFalse(); }
### Question: ChainedTypeConverter implements TypeConverter<Object> { @Override public Object fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return converterFor(type, attributes).fromString(type, value, attributes); } ChainedTypeConverter(List<TypeConverter<?>> converters); ChainedTypeConverter(TypeConverter<?>... converters); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override Object fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Object value, Map<String, String> attributes); }### Answer: @Test public void shouldThrowIAEWhenTypeIsNotSupported() { assertThrows(IllegalArgumentException.class, () -> { TypeConverter<Object> converter = new ChainedTypeConverter(new StringConverter()); converter.fromString(Long.class, "10", null); }); }
### Question: FloatConverter extends AbstractNumberConverter<Float> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Float.class, Float.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableWhenFloatType() { Type type = Float.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotFloatType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: UrlConverter implements TypeConverter<URL> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && URL.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override URL fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, URL value, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableWhenUrlType() { Type type = URL.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotUrlType() { Type type = Boolean.class; boolean applicable = converter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> converter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: UrlConverter implements TypeConverter<URL> { @Override public String toString(Type type, URL value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return Objects.toString(value, null); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override URL fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, URL value, Map<String, String> attributes); }### Answer: @Test public void shouldConvertToString() throws MalformedURLException { String urlString = "http: URL toConvert = new URL(urlString); String converted = converter.toString(URL.class, toConvert, emptyMap()); assertThat(converted).isEqualTo(urlString); } @Test public void shouldReturnNullWhenConvertingToStringAndValueToConvertIsNull() { String converted = converter.toString(URL.class, null, emptyMap()); assertThat(converted).isNull(); }
### Question: UrlConverter implements TypeConverter<URL> { @Override public URL fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { return new URL(value); } catch (MalformedURLException e) { throw new IllegalArgumentException(format("Unable to convert to URL: %s", value), e); } } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override URL fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, URL value, Map<String, String> attributes); }### Answer: @Test public void shouldCovertFromString() throws MalformedURLException { String urlInString = "http: URL fromConversion = converter.fromString(URL.class, urlInString, emptyMap()); URL expected = new URL(urlInString); assertThat(fromConversion).isEqualTo(expected); } @Test public void shouldThrowExceptionWhenMalformedUrl() { String malformedUrlString = "malformed URL"; assertThatThrownBy(() -> converter.fromString(URL.class, malformedUrlString, emptyMap())) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Unable to convert to URL: malformed URL"); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndTypeIsNull() { String urlInString = "http: assertThatThrownBy(() -> converter.fromString(null, urlInString, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); } @Test public void shouldReturnNullWhenConvertingFromStringAndValueToConvertIsNull() { URL fromConversion = converter.fromString(URL.class, null, emptyMap()); assertThat(fromConversion).isNull(); }
### Question: ShortConverter extends AbstractNumberConverter<Short> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { return isApplicable(type, Short.class, Short.TYPE); } @Override boolean isApplicable(Type type, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableWhenShortType() { Type type = Short.class; boolean applicable = shortTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isTrue(); } @Test public void shouldNotBeApplicableWhenNotShortType() { Type type = Boolean.class; boolean applicable = shortTypeConverter.isApplicable(type, emptyMap()); assertThat(applicable).isFalse(); } @Test public void shouldThrowExceptionWhenCheckingIfApplicableAndTypeIsNull() { assertThatThrownBy(() -> shortTypeConverter.isApplicable(null, emptyMap())) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: EnumConverter implements TypeConverter<Enum<?>> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class<?> && Enum.class.isAssignableFrom((Class<?>) type); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override Enum<?> fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Enum<?> value, Map<String, String> attributes); }### Answer: @Test public void shouldAcceptEnumType() { Type type = TestEnum.class; boolean isApplicable = enumTypeAdapter.isApplicable(type, null); assertThat(isApplicable).isTrue(); }
### Question: EnumConverter implements TypeConverter<Enum<?>> { @SuppressWarnings("unchecked") @Override public Enum<?> fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : toEnumValue((Class<Enum<?>>) type, value); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override Enum<?> fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Enum<?> value, Map<String, String> attributes); }### Answer: @Test public void shouldConvertFromString() { Enum<?> testEnum = enumTypeAdapter.fromString(TestEnum.class, "FIRST", null); assertThat(testEnum).isEqualTo(TestEnum.FIRST); } @Test public void shouldThrowExceptionWhenConvertingFromStringAndWrongValue() { String value = "WRONG_VALUE"; assertThatThrownBy(() -> enumTypeAdapter.fromString(TestEnum.class, value, null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unable to convert a value to an enumeration:"); }
### Question: EnumConverter implements TypeConverter<Enum<?>> { @Override public String toString(Type type, Enum<?> value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return value == null ? null : value.name(); } @Override boolean isApplicable(Type type, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override Enum<?> fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, Enum<?> value, Map<String, String> attributes); }### Answer: @Test public void shouldConvertToString() { String value = enumTypeAdapter.toString(TestEnum.class, TestEnum.SECOND_VALUE, null); assertThat(value).isEqualTo(TestEnum.SECOND_VALUE.name()); }
### Question: JsonConverter implements TypeConverter<T> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); String converter = (attributes == null) ? null : attributes.get(CONVERTER); return ignoreConverterAttribute || Objects.equals(converter, JSON); } JsonConverter(); JsonConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer: @Test void shouldThrowExceptionWhenTypeIsNullAndIsApplicable() { assertThatThrownBy(() -> typeConverter.isApplicable(null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: MetaDataExample { public static void main(String[] args) { new MetaDataExample().run(); } static void main(String[] args); }### Answer: @Test public void shouldExecuteMainWithoutExceptions() { MetaDataExample.main(new String[0]); }
### Question: JsonConverter implements TypeConverter<T> { @Override public String toString(Type type, T value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { ObjectWriter objectWriter = objectMapper.writer(); return objectWriter.writeValueAsString(value); } catch (JsonProcessingException e) { throw new UncheckedIOException("Unable to process JSON.", e); } } JsonConverter(); JsonConverter(boolean ignoreConverterAttribute); @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer: @Test void shouldConvertToString() { TestClass toConvert = new TestClass(); toConvert.integer = 10; toConvert.string = "test"; String converted = typeConverter.toString(TestClass.class, toConvert, null); assertThat(converted).isEqualTo("" + "{" + "\"integer\":10," + "\"string\":\"test\"" + "}"); } @Test void shouldReturnNullWhenToStringAndValueIsNull() { String converted = typeConverter.toString(TestClass.class, null, null); assertThat(converted).isNull(); } @Test void shouldThrowExceptionWhenTypeIsNullAndToString() { assertThatThrownBy(() -> typeConverter.toString(null, null, null)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage("type cannot be null"); }
### Question: SpringAnnotationBasedExample { public static void main(String[] args) { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringAnnotationBasedExample.class)) { context.getBean(SpringAnnotationBasedExample.class).run(); } } static void main(String[] args); }### Answer: @Test public void shouldExecuteMainWithoutExceptions() { SpringAnnotationBasedExample.main(new String[0]); }
### Question: SpringExample { public static void main(String[] args) { new SpringExample().run(); } static void main(String[] args); }### Answer: @Test public void shouldExecuteMainWithoutExceptions() { SpringExample.main(new String[0]); }
### Question: CoreExample { public static void main(String[] args) { new CoreExample().run(); } static void main(String[] args); }### Answer: @Test public void shouldExecuteMainWithoutExceptions() { CoreExample.main(new String[0]); }
### Question: MethodsProvider { public Collection<Method> getAllDeclaredMethods(Class<?> configurationType) { Class<?> type = configurationType; Set<MethodWrapper> methods = new LinkedHashSet<>(addMethods(type.getMethods())); if (type.getSuperclass() != null) { do { methods.addAll(addMethods(type.getDeclaredMethods())); type = type.getSuperclass(); } while (!Object.class.equals(type)); } return methods.stream() .map(MethodWrapper::getMethod) .collect(toList()); } Collection<Method> getAllDeclaredMethods(Class<?> configurationType); }### Answer: @Test public void shouldFindPublicAbstractMethodInClass() throws NoSuchMethodException { abstract class TestClass { public abstract int propertyA(); } Collection<Method> methods = methodsProvider.getAllDeclaredMethods(TestClass.class); assertThat(methods).contains(TestClass.class.getMethod("propertyA")); } @Test public void shouldFindPublicAbstractMethodInheritedFromAbstractMethod() throws NoSuchMethodException { abstract class AbstractClass { public abstract int propertyA(); } abstract class TestClass extends AbstractClass { public abstract int propertyB(); } Collection<Method> methods = methodsProvider.getAllDeclaredMethods(TestClass.class); assertThat(methods).contains(AbstractClass.class.getMethod("propertyA"), TestClass.class.getMethod("propertyB")); } @Test public void shouldFindMethodInheritedFromInterface() throws NoSuchMethodException { abstract class TestClass implements TestInterface { public abstract int propertyB(); } Collection<Method> methods = methodsProvider.getAllDeclaredMethods(TestClass.class); assertThat(methods).contains(TestInterface.class.getMethod("propertyA"), TestClass.class.getMethod("propertyB")); } @Test public void shouldHandleMethodFromSubclass() throws NoSuchMethodException { abstract class BaseConf { public abstract Integer propertyA(); } abstract class SpecificConf extends BaseConf { @Override public abstract Integer propertyA(); } abstract class AbstractClass { public abstract BaseConf propertyB(); } abstract class TestClass extends AbstractClass { @Override public abstract SpecificConf propertyB(); } Collection<Method> methods = methodsProvider.getAllDeclaredMethods(TestClass.class); assertThat(methods).contains(TestClass.class.getMethod("propertyB")); }
### Question: PropertySourceConfigurationSource implements ConfigurationSource, BeanFactoryAware, EnvironmentAware, InitializingBean { @Override public OptionalValue<String> getValue(String key, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); for (PropertySource<?> propertySource : flattenedPropertySources) { OptionalValue<String> value = getProperty(propertySource, key); if (value.isPresent()) { return value; } } return absent(); } void setPropertySources(PropertySources propertySources); @Override void setBeanFactory(BeanFactory beanFactory); @Override void setEnvironment(Environment environment); void setConversionService(ConversionService conversionService); @Override void afterPropertiesSet(); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override ConfigurationEntry findEntry(Collection<String> keys, Map<String, String> attributes); }### Answer: @Test public void shouldResolvePropertyPlaceholdersSetWithCorrectOrder() { assertThat(source.getValue("property.only.in.A", null)).isEqualTo(present("A")); assertThat(source.getValue("property.only.in.B", null)).isEqualTo(present("B")); assertThat(source.getValue("property.in.A.and.B", null)).isEqualTo(present("B")); }
### Question: AttributesUtils implements Serializable { public static Map<String, String> attributes(Map<String, String> attributes) { return getCached(attributes, true); } private AttributesUtils(); static Map<String, String> attributes(Map<String, String> attributes); static Map<String, String> mergeAttributes(Map<String, String> parent, Map<String, String> child); }### Answer: @Test public void shouldReturnNullWhenPropertiesAreNull() { Map<String, String> properties = null; Map<String, String> attributes = attributes(properties); assertThat(attributes).isNull(); } @Test public void shouldConstructFromMap() { Map<String, String> properties = MapUtils.of("key1", "val1", "key2", "val2"); Map<String, String> attributes = attributes(properties); assertThat(attributes).isNotNull(); assertThat(attributes).contains(entry("key1", "val1"), entry("key2", "val2")); } @Test public void shouldBeImmutable() { assertThrows(UnsupportedOperationException.class, () -> attributes(MapUtils.of("key", "value")).put("anything", "value") ); } @Test public void shouldProvideSameInstanceForSameProperties() { Map<String, String> properties = MapUtils.of("key1", "value1", "key2", "value2"); Map<String, String> sameProperties = new HashMap<>(properties); Map<String, String> attributes = attributes(properties); Map<String, String> attributesForSameProperties = attributes(sameProperties); assertThat(attributesForSameProperties).isSameAs(attributes); }
### Question: AttributesUtils implements Serializable { public static Map<String, String> mergeAttributes(Map<String, String> parent, Map<String, String> child) { if (parent == null) { return getCached(child, true); } if (child == null) { return getCached(parent, true); } Map<String, String> merged = new LinkedHashMap<>(parent.size() + child.size()); merged.putAll(parent); merged.putAll(child); return getCached(unmodifiableMap(merged), false); } private AttributesUtils(); static Map<String, String> attributes(Map<String, String> attributes); static Map<String, String> mergeAttributes(Map<String, String> parent, Map<String, String> child); }### Answer: @Test public void shouldMergeToNullWhenBothAreNull() { Map<String, String> merged = mergeAttributes(null, null); assertThat(merged).isNull(); }
### Question: CachingTypeConverter implements TypeConverter<T>, InitializingBean { @SuppressWarnings("unchecked") @Override public T fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); SimpleKey key = new SimpleKey(type, attributes, value); ValueWrapper valueWrapper = cache.get(key); if (valueWrapper != null) { return (T) valueWrapper.get(); } else { T val = typeConverter.fromString(type, value, attributes); valueWrapper = cache.putIfAbsent(key, val); if (valueWrapper == null) { return val; } else { return (T) valueWrapper.get(); } } } TypeConverter<?> getTypeConverter(); void setTypeConverter(TypeConverter<T> typeConverter); CacheManager getCacheManager(); void setCacheManager(CacheManager cacheManager); String getCacheName(); void setCacheName(String cacheName); @Override void afterPropertiesSet(); @Override boolean isApplicable(Type type, Map<String, String> attributes); @SuppressWarnings("unchecked") @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer: @Test public void shouldIntegrateWithSpring() { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class)) { TypeConverter<?> typeConverter = context.getBean(TypeConverter.class); assertThat(typeConverter).isInstanceOf(CachingTypeConverter.class); Long val = (Long) typeConverter.fromString(Long.class, "10", null); Long val2 = (Long) typeConverter.fromString(Long.class, "10", null); assertThat(val).isEqualTo(10L); assertThat(val2).isSameAs(val); SampleConfiguration configuration = context.getBean(SampleConfiguration.class); Long valueFromConfiguration = configuration.getValue(); assertThat(valueFromConfiguration).isEqualTo(10L); assertThat(valueFromConfiguration).isSameAs(val); } }
### Question: PropertyUtils { public static Object getProperty(Object bean, String name) { requireNonNull(bean, "bean cannot be null"); requireNonNull(name, "name cannot be null"); Class<?> beanClass = bean.getClass(); try { PropertyDescriptor descriptor = findPropertyDescriptor(beanClass, name); Method readMethod = descriptor.getReadMethod(); return readMethod.invoke(bean, EMPTY_OBJECT_ARRAY); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalArgumentException("Unable to get property " + name + " on " + bean.getClass(), e); } } private PropertyUtils(); static String getPropertyName(Method method); static Object getProperty(Object bean, String name); static void setProperty(Object bean, String name, Object value); }### Answer: @Test public void shouldGetProperties() { Bean bean = new Bean(); assertThat(getProperty(bean, "intValue")).isEqualTo(0); assertThat(getProperty(bean, "stringValue")).isNull(); assertThat(getProperty(bean, "beanValue")).isNull(); bean.setIntValue(1); assertThat(getProperty(bean, "intValue")).isEqualTo(bean.getIntValue()); bean.setStringValue("string"); assertThat(getProperty(bean, "stringValue")).isSameAs(bean.getStringValue()); bean.setBeanValue(new Bean()); assertThat(getProperty(bean, "beanValue")).isSameAs(bean.getBeanValue()); } @Test public void getPropertyShouldThrowNoSuchMethodExceptionWhenPropertyNotFound() { assertThrows(IllegalArgumentException.class, () -> getProperty(new Bean(), "unknownProperty")); } @Test public void getPropertyShouldThrowNoSuchMethodExceptionWhenPropertyIsCapitalized() { assertThrows(IllegalArgumentException.class, () -> getProperty(new Bean(), "BeanValue")); } @Test public void getPropertyShouldThrowNullPointerExceptionWhenNullBean() { assertThrows(NullPointerException.class, () -> getProperty(null, "intValue")); } @Test public void getPropertyShouldThrowNullPointerExceptionWhenNullPropertyName() { assertThrows(NullPointerException.class, () -> getProperty(new Bean(), null)); }
### Question: JaxbConverter implements TypeConverter<T> { @Override public boolean isApplicable(Type type, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); return type instanceof Class && ((AnnotatedElement) type).getAnnotation(XmlRootElement.class) != null; } @Override boolean isApplicable(Type type, Map<String, String> attributes); @Override T fromString(Type type, String value, Map<String, String> attributes); @Override String toString(Type type, T value, Map<String, String> attributes); }### Answer: @Test public void shouldBeApplicableForMultipleXmlTypes() { assertThat(jaxbTypeConverter.isApplicable(XmlRootConfiguration01.class, null)).isTrue(); assertThat(jaxbTypeConverter.isApplicable(XmlRootConfiguration02.class, null)).isTrue(); } @Test public void shouldNotBeApplicableForNonXmlTypes() { assertThat(jaxbTypeConverter.isApplicable(NonXmlConfiguration.class, null)).isFalse(); }
### Question: PropertyUtils { public static String getPropertyName(Method method) { requireNonNull(method, "method cannot be null"); String name = method.getName(); if (name.startsWith("set")) { if (method.getParameterCount() != 1) { throw new IllegalArgumentException("Method " + method + " is not a valid setter."); } name = name.substring(3); } else if (name.startsWith("get") || name.startsWith("is")) { if (method.getParameterCount() != 0 || void.class.equals(method.getReturnType())) { throw new IllegalArgumentException("Method " + method + " is not a valid getter."); } name = name.substring(name.startsWith("get") ? 3 : 2); } else { throw new IllegalArgumentException("Method " + name + " is not a valid getter nor setter."); } return decapitalize(name); } private PropertyUtils(); static String getPropertyName(Method method); static Object getProperty(Object bean, String name); static void setProperty(Object bean, String name, Object value); }### Answer: @Test public void getPropertyNameShouldProvidePropertyNameFromValidAccessor() { assertThat(getPropertyName(getMethod(Bean.class, "getIntValue"))).isEqualTo("intValue"); assertThat(getPropertyName(getMethod(Bean.class, "setIntValue"))).isEqualTo("intValue"); assertThat(getPropertyName(getMethod(Bean.class, "getStringValue"))).isEqualTo("stringValue"); assertThat(getPropertyName(getMethod(Bean.class, "isBooleanValue"))).isEqualTo("booleanValue"); assertThat(getPropertyName(getMethod(Bean.class, "setBooleanValue"))).isEqualTo("booleanValue"); } @Test public void getPropertyNameShouldThrowNPEWhenMethodIsNull() { assertThrows(NullPointerException.class, () -> getPropertyName(null)); } @Test public void getPropertyNameShouldThrowIAEWhenMethodIsNotGetterNorSetter() { assertThrows(IllegalArgumentException.class, () -> getPropertyName(getMethod(Bean.class, "equals"))); }
### Question: MultiConfigurationSource implements ConfigurationSource { @Override public OptionalValue<String> getValue(String key, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); for (ConfigurationSource source : sources) { OptionalValue<String> value = source.getValue(key, attributes); if (value.isPresent()) { return value; } } return absent(); } MultiConfigurationSource(List<ConfigurationSource> sources); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override ConfigurationEntry findEntry(Collection<String> keys, Map<String, String> attributes); }### Answer: @Test public void shouldReturnValuesFromProperSource() { assertThat(source.getValue(A_KEY, null).get()).isEqualTo(A_KEY); assertThat(source.getValue(B_KEY, null).get()).isEqualTo(B_KEY); }
### Question: MultiConfigurationSource implements ConfigurationSource { @Override public ConfigurationEntry findEntry(Collection<String> keys, Map<String, String> attributes) { requireNonNull(keys, "keys cannot be null"); for (ConfigurationSource source : sources) { ConfigurationEntry entry = source.findEntry(keys, attributes); if (entry != null) { return entry; } } return null; } MultiConfigurationSource(List<ConfigurationSource> sources); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override ConfigurationEntry findEntry(Collection<String> keys, Map<String, String> attributes); }### Answer: @Test public void shouldFindValuesInProperSource() { assertThat(source.findEntry(asList("NotExistingKey", B_KEY), null)).isEqualTo(new ConfigurationEntry(B_KEY, B_KEY)); }
### Question: MapConfigurationSource implements IterableConfigurationSource { @Override public OptionalValue<String> getValue(String key, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); String value = source.get(key); return value != null || source.containsKey(key) ? present(value) : absent(); } MapConfigurationSource(Map<String, String> source); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override Iterable<ConfigurationEntry> getAllConfigurationEntries(); }### Answer: @Test public void shouldGetSingleValueFromUnderlyingMap() { ConfigurationSource source = new MapConfigurationSource(of("key1", "value1", "key2", "value2")); String value = source.getValue("key2", null).get(); assertThat(value).isEqualTo("value2"); }
### Question: MapConfigurationSource implements IterableConfigurationSource { @Override public Iterable<ConfigurationEntry> getAllConfigurationEntries() { return new MapConfigurationEntryIterable(source); } MapConfigurationSource(Map<String, String> source); @Override OptionalValue<String> getValue(String key, Map<String, String> attributes); @Override Iterable<ConfigurationEntry> getAllConfigurationEntries(); }### Answer: @Test public void shouldIterateOver() { MapConfigurationSource source = new MapConfigurationSource(of("key1", "value1", "key2", "value2")); Iterable<ConfigurationEntry> iterable = source.getAllConfigurationEntries(); assertThat(iterable).containsExactly(new ConfigurationEntry("key1", "value1"), new ConfigurationEntry("key2", "value2")); }
### Question: WritableMapConfigurationSource extends MapConfigurationSource implements WritableConfigurationSource { @Override public void setValue(String key, String value, Map<String, String> attributes) { requireNonNull(key, "key cannot be null"); source.put(key, value); } WritableMapConfigurationSource(Map<String, String> source); @Override void setValue(String key, String value, Map<String, String> attributes); @Override OptionalValue<String> removeValue(String key, Map<String, String> attributes); }### Answer: @Test public void shouldSetAndGetValue() { WritableConfigurationSource mapConfigurationSource = new WritableMapConfigurationSource(new HashMap<>()); mapConfigurationSource.setValue("key", "value", null); OptionalValue<String> value = mapConfigurationSource.getValue("key", null); assertThat(value.isPresent()).isTrue(); assertThat(value.get()).isEqualTo("value"); }
### Question: AvgLaborCostCalcForOrderDetailsHooks { public void enabledButtonForCopyNorms(final ViewDefinitionState view) { WindowComponent window = (WindowComponent) view.getComponentByReference("window"); RibbonActionItem copyToOperationsNorms = window.getRibbon().getGroupByName("hourlyCostNorms") .getItemByName("copyToOperationsNorms"); FieldComponent averageLaborHourlyCost = (FieldComponent) view.getComponentByReference(AVERAGE_LABOR_HOURLY_COST); if (StringUtils.isEmpty((String) averageLaborHourlyCost.getFieldValue())) { copyToOperationsNorms.setEnabled(false); } else { copyToOperationsNorms.setEnabled(true); } copyToOperationsNorms.requestUpdate(true); } void enabledButtonForCopyNorms(final ViewDefinitionState view); }### Answer: @Test public void shouldEnabledButtonForCopyNorms() throws Exception { String averageLaborHourlyCostValue = "50"; when(averageLaborHourlyCost.getFieldValue()).thenReturn(averageLaborHourlyCostValue); orderDetailsHooks.enabledButtonForCopyNorms(view); Mockito.verify(copyToOperationsNorms).setEnabled(true); } @Test public void shouldDisbaleButtonForCopyNorms() throws Exception { String averageLaborHourlyCostValue = ""; when(averageLaborHourlyCost.getFieldValue()).thenReturn(averageLaborHourlyCostValue); orderDetailsHooks.enabledButtonForCopyNorms(view); Mockito.verify(copyToOperationsNorms).setEnabled(false); }
### Question: GenerateProductionBalanceWithCosts implements Observer { void generateBalanceWithCostsReport(final Entity productionBalance) { Locale locale = LocaleContextHolder.getLocale(); String localePrefix = "productionCounting.productionBalanceWithCosts.report.fileName"; Entity productionBalanceWithFileName = fileService.updateReportFileName(productionBalance, ProductionBalanceFields.DATE, localePrefix); String localePrefixToMatch = localePrefix; try { productionBalanceWithCostsPdfService.generateDocument(productionBalanceWithFileName, locale, localePrefixToMatch); productionBalanceWithFileName.setField(ProductionBalanceFieldsPCWC.GENERATED_WITH_COSTS, Boolean.TRUE); productionBalanceWithFileName.getDataDefinition().save(productionBalanceWithFileName); } catch (IOException e) { throw new IllegalStateException("Problem with saving productionBalanceWithCosts report", e); } catch (DocumentException e) { throw new IllegalStateException("Problem with generating productionBalanceWithCosts report", e); } } @Override void update(final Observable observable, final Object object); void doTheCostsPart(final Entity productionBalance); void fillFieldsAndGrids(final Entity productionBalance); }### Answer: @Test public void shouldGenerateReportCorrectly() throws Exception { Locale locale = Locale.getDefault(); String localePrefix = "productionCounting.productionBalanceWithCosts.report.fileName"; Entity productionBalanceWithFileName = mock(Entity.class); given(productionBalanceWithFileName.getDataDefinition()).willReturn(productionBalanceDD); given(fileService.updateReportFileName(productionBalance, ProductionBalanceFields.DATE, localePrefix)).willReturn( productionBalanceWithFileName); generateProductionBalanceWithCosts.generateBalanceWithCostsReport(productionBalance); verify(productionBalanceWithCostsPdfService).generateDocument(productionBalanceWithFileName, locale, localePrefix); verify(productionBalanceWithFileName).setField(ProductionBalanceFieldsPCWC.GENERATED_WITH_COSTS, Boolean.TRUE); verify(productionBalanceDD).save(productionBalanceWithFileName); }
### Question: ProductDetailsListenersT { public final void addTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args) { FormComponent productForm = (FormComponent) view.getComponentByReference(L_FORM); Entity product = productForm.getEntity(); if (product.getId() == null) { return; } Map<String, Object> parameters = Maps.newHashMap(); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologyGroups"); String url = "../page/technologies/technologyGroupDetails.html"; view.redirectTo(url, false, true, parameters); } final void addTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithTechnologyGroup(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithProduct(final ViewDefinitionState view, final ComponentState componentState, final String[] args); final void showTechnologiesWithUsingProduct(final ViewDefinitionState view, final ComponentState state, final String[] args); }### Answer: @Test public void shouldntAddTechnologyGroupIfProductIsntSaved() { given(product.getId()).willReturn(null); String url = "../page/technologies/technologyGroupDetails.html"; productDetailsListenersT.addTechnologyGroup(view, null, null); verify(view, never()).redirectTo(url, false, true, parameters); } @Test public void shouldAddTechnologyGroupIfProductIsSaved() { given(product.getId()).willReturn(L_ID); parameters.put(L_WINDOW_ACTIVE_MENU, "technology.technologyGroups"); String url = "../page/technologies/technologyGroupDetails.html"; productDetailsListenersT.addTechnologyGroup(view, null, null); verify(view).redirectTo(url, false, true, parameters); }
### Question: CostNormsForOperationService { public void fillCurrencyFields(final ViewDefinitionState view) { String currencyStringCode = currencyService.getCurrencyAlphabeticCode(); FieldComponent component = null; for (String componentReference : Sets.newHashSet("pieceworkCostCURRENCY", "laborHourlyCostCURRENCY", "machineHourlyCostCURRENCY")) { component = (FieldComponent) view.getComponentByReference(componentReference); if (component == null) { continue; } component.setFieldValue(currencyStringCode); component.requestComponentUpdateState(); } } void copyCostValuesFromOperation(final ViewDefinitionState view, final ComponentState operationLookupState, final String[] args); void inheritOperationNormValues(final ViewDefinitionState view, final ComponentState componentState, final String[] args); void fillCurrencyFields(final ViewDefinitionState view); void copyCostNormsToTechnologyOperationComponent(final DataDefinition dd, final Entity technologyOperationComponent); }### Answer: @Test public void shouldFillCurrencyFields() throws Exception { String currency = "PLN"; when(currencyService.getCurrencyAlphabeticCode()).thenReturn(currency); when(view.getComponentByReference("pieceworkCostCURRENCY")).thenReturn(field1); when(view.getComponentByReference("laborHourlyCostCURRENCY")).thenReturn(field2); when(view.getComponentByReference("machineHourlyCostCURRENCY")).thenReturn(field3); costNormsForOperationService.fillCurrencyFields(view); Mockito.verify(field1).setFieldValue(currency); Mockito.verify(field2).setFieldValue(currency); Mockito.verify(field3).setFieldValue(currency); }
### Question: ProductionLinesServiceImpl implements ProductionLinesService { @Override public Integer getWorkstationTypesCount(final Entity operationComponent, final Entity productionLine) { List<Entity> workstationTypeComponents = productionLine.getHasManyField(ProductionLineFields.WORKSTATION_TYPE_COMPONENTS); Entity desiredWorkstation = operationComponent.getBelongsToField(TechnologyOperationComponentFields.OPERATION) .getBelongsToField(OperationFields.WORKSTATION_TYPE); if (desiredWorkstation != null) { for (Entity workstationTypeComponent : workstationTypeComponents) { Entity workstation = workstationTypeComponent.getBelongsToField(OperationFields.WORKSTATION_TYPE); if (desiredWorkstation.getId().equals(workstation.getId())) { return (Integer) workstationTypeComponent.getField(WorkstationTypeComponentFields.QUANTITY); } } } return productionLine.getIntegerField(ProductionLineFields.QUANTITY_FOR_OTHER_WORKSTATION_TYPES); } @Override Integer getWorkstationTypesCount(final Entity operationComponent, final Entity productionLine); @Override Integer getWorkstationTypesCount(final Long productionLineId, final String workstationTypeNumber); }### Answer: @Test public void shouldReturnCorrectWorkstationCount() { given(operation.getBelongsToField("workstationType")).willReturn(work2); Integer workstationCount = productionLinesServiceImpl.getWorkstationTypesCount(opComp1, productionLine); assertEquals(Integer.valueOf(234), workstationCount); } @Test public void shouldReturnSpecifiedQuantityIfNoWorkstationIsFound() { given(productionLine.getIntegerField("quantityForOtherWorkstationTypes")).willReturn(456); given(operation.getBelongsToField("workstationType")).willReturn(work3); Integer workstationCount = productionLinesServiceImpl.getWorkstationTypesCount(opComp1, productionLine); assertEquals(Integer.valueOf(456), workstationCount); }