method2testcases
stringlengths 118
3.08k
|
---|
### Question:
AtomicFloat extends Number implements java.io.Serializable { public final float incrementAndGet() { return addAndGet(1.0f); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testIncrementAndGet() { float val; for (int i=0; i<10; ++i) { val = af.get(); assertEquals((float)(i ),val,1.0E-8); val = af.incrementAndGet(); assertEquals((float)(i+1),val,1.0E-8); val = af.get(); assertEquals((float)(i+1),val,1.0E-8); } } |
### Question:
AtomicFloat extends Number implements java.io.Serializable { public final float decrementAndGet() { return addAndGet(-1.0f); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testDecrementAndGet() { float val = 10.0f; af.set(val); for (int i=10; i>0; --i) { val = af.get(); assertEquals((float)(i ),val,1.0E-8); val = af.decrementAndGet(); assertEquals((float)(i-1),val,1.0E-8); val = af.get(); assertEquals((float)(i-1),val,1.0E-8); } } |
### Question:
AtomicFloat extends Number implements java.io.Serializable { public final float getAndIncrement() { return getAndAdd(1.0f); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testGetAndIncrement() { float val; for (int i=0; i<10; ++i) { val = af.get(); assertEquals((float)(i ),val,1.0E-8); val = af.getAndIncrement(); assertEquals((float)(i ),val,1.0E-8); val = af.get(); assertEquals((float)(i+1),val,1.0E-8); } } |
### Question:
AtomicFloat extends Number implements java.io.Serializable { public final float getAndDecrement() { return getAndAdd(-1.0f); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testGetAndDecrement() { float val = 10.0f; af.set(val); for (int i=10; i>0; --i) { val = af.get(); assertEquals((float)(i ),val,1.0E-8); val = af.getAndDecrement(); assertEquals((float)(i ),val,1.0E-8); val = af.get(); assertEquals((float)(i-1),val,1.0E-8); } } |
### Question:
AtomicFloat extends Number implements java.io.Serializable { public final float getAndSet(float value) { return f(_ai.getAndSet(i(value))); } AtomicFloat(); AtomicFloat(float value); final float get(); final void set(float value); final float getAndSet(float value); final boolean compareAndSet(float expect, float update); final boolean weakCompareAndSet(float expect, float update); final float getAndIncrement(); final float getAndDecrement(); final float getAndAdd(float delta); final float incrementAndGet(); final float decrementAndGet(); final float addAndGet(float delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testGetAndSet() { float expected0 = RANDOM.nextFloat(); float expected1 = RANDOM.nextFloat(); AtomicFloat af = new AtomicFloat(expected0); float actual0 = af.getAndSet(expected1); float actual1 = af.get(); assertEquals(expected0,actual0,epsilon); assertEquals(expected1,actual1,epsilon); } |
### Question:
AtomicDouble extends Number implements java.io.Serializable { public final double get() { return d(_al.get()); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testDefaultConstructor() { assertEquals(0.0,ad.get(),epsilon); }
@Test public void testConstructorSingleParameter() { double expected = RANDOM.nextDouble(); AtomicDouble ad = new AtomicDouble(expected); assertEquals(expected,ad.get(),epsilon); } |
### Question:
AtomicDouble extends Number implements java.io.Serializable { public final void set(double value) { _al.set(l(value)); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testSet() { double expected = RANDOM.nextDouble(); ad.set(expected); assertEquals(expected, ad.get(),epsilon); } |
### Question:
CleanFormatter extends Formatter { public static String prependToLines(String prepend, String lines) { if (lines == null) return null; if (prepend == null) return lines; StringBuilder result = new StringBuilder(); boolean hasFinalNL = lines.endsWith(NL); StringTokenizer divided = new StringTokenizer(lines, NL); while (divided.hasMoreTokens()) { result.append(prepend); result.append(divided.nextToken()); if (divided.hasMoreTokens() || hasFinalNL) result.append(NL); } return result.toString(); } static void setWarningPrefix(String prefix); @Override synchronized String format(LogRecord record); static String prependToLines(String prepend, String lines); }### Answer:
@Test public void testPrepend() { String lines = CleanFormatter.prependToLines("a","bbb"+NL+"ccc"); assertTrue(lines.equals("abbb"+NL+"accc")); } |
### Question:
AtomicDouble extends Number implements java.io.Serializable { public final double addAndGet(double delta) { for (;;) { long lexpect = _al.get(); double expect = d(lexpect); double update = expect+delta; long lupdate = l(update); if (_al.compareAndSet(lexpect,lupdate)) return update; } } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testAddAndGet() { double expected = 0.0; for (int i=0; i<10; ++i) { double nd = RANDOM.nextDouble(); expected += nd; double actual = ad.addAndGet(nd); assertEquals(expected, ad.get(),epsilon); } } |
### Question:
AtomicDouble extends Number implements java.io.Serializable { public final boolean compareAndSet(double expect, double update) { return _al.compareAndSet(l(expect),l(update)); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testCompareAndSet() { ad.compareAndSet(1.0,2.0); assertEquals(0.0,ad.get()); ad.compareAndSet(0.0,1.0); assertEquals(1.0,ad.get()); } |
### Question:
AtomicDouble extends Number implements java.io.Serializable { public final boolean weakCompareAndSet(double expect, double update) { return _al.weakCompareAndSet(l(expect),l(update)); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testWeakCompareAndSet() { ad.weakCompareAndSet(0.0,1.0); assertEquals(1.0,ad.get()); } |
### Question:
AtomicDouble extends Number implements java.io.Serializable { public final double incrementAndGet() { return addAndGet(1.0); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testIncrementAndGet() { double val; for (int i=0; i<10; ++i) { val = ad.get(); assertEquals((double)(i ),val,1.0E-8); val = ad.incrementAndGet(); assertEquals((double)(i+1),val,1.0E-8); val = ad.get(); assertEquals((double)(i+1),val,1.0E-8); } } |
### Question:
AtomicDouble extends Number implements java.io.Serializable { public final double decrementAndGet() { return addAndGet(-1.0); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testDecrementAndGet() { double val = 10.0; ad.set(val); for (int i=10; i>0; --i) { val = ad.get(); assertEquals((double)(i ),val,1.0E-8); val = ad.decrementAndGet(); assertEquals((double)(i-1),val,1.0E-8); val = ad.get(); assertEquals((double)(i-1),val,1.0E-8); } } |
### Question:
AtomicDouble extends Number implements java.io.Serializable { public final double getAndIncrement() { return getAndAdd(1.0); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testGetAndIncrement() { double val; for (int i=0; i<10; ++i) { val = ad.get(); assertEquals((double)(i ),val,1.0E-8); val = ad.getAndIncrement(); assertEquals((double)(i ),val,1.0E-8); val = ad.get(); assertEquals((double)(i+1),val,1.0E-8); } } |
### Question:
AtomicDouble extends Number implements java.io.Serializable { public final double getAndDecrement() { return getAndAdd(-1.0); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testGetAndDecrement() { double val = 10.0; ad.set(val); for (int i=10; i>0; --i) { val = ad.get(); assertEquals((double)(i ),val,1.0E-8); val = ad.getAndDecrement(); assertEquals((double)(i ),val,1.0E-8); val = ad.get(); assertEquals((double)(i-1),val,1.0E-8); } } |
### Question:
AtomicDouble extends Number implements java.io.Serializable { public final double getAndSet(double value) { return d(_al.getAndSet(l(value))); } AtomicDouble(); AtomicDouble(double value); final double get(); final void set(double value); final double getAndSet(double value); final boolean compareAndSet(double expect, double update); final boolean weakCompareAndSet(double expect, double update); final double getAndIncrement(); final double getAndDecrement(); final double getAndAdd(double delta); final double incrementAndGet(); final double decrementAndGet(); final double addAndGet(double delta); String toString(); int intValue(); long longValue(); float floatValue(); double doubleValue(); }### Answer:
@Test public void testGetAndSet() { double expected0 = RANDOM.nextDouble(); double expected1 = RANDOM.nextDouble(); AtomicDouble ad = new AtomicDouble(expected0); double actual0 = ad.getAndSet(expected1); double actual1 = ad.get(); assertEquals(expected0,actual0,epsilon); assertEquals(expected1,actual1,epsilon); } |
### Question:
RTree extends AbstractSet<Object> { public Iterator<Object> iterator() { return new RTreeIterator(); } RTree(int ndim, int nmin, int nmax); RTree(int ndim, int nmin, int nmax, Boxer boxer); int size(); void clear(); boolean isEmpty(); boolean add(Object object); int addPacked(Object[] objects); boolean remove(Object object); boolean contains(Object object); Iterator<Object> iterator(); int getLevels(); Object[] findOverlapping(float[] min, float[] max); Object[] findOverlapping(Box box); Object[] findInSphere(float[] center, float radius); Object findNearest(float[] point); Object[] findNearest(int k, float[] point); float getLeafArea(); float getLeafVolume(); void dump(); void validate(); }### Answer:
@Test public void testIterator() { RTree rt = new RTree(3,4,12); int n = 100; for (int i=0; i<n; ++i) rt.add(randomBox(0.2f)); Iterator<Object> rti = rt.iterator(); Object box = rti.next(); rt.remove(box); rt.add(box); boolean cmeThrown = false; try { rti.next(); } catch (ConcurrentModificationException cme) { cmeThrown = true; } assertTrue(cmeThrown); Object[] boxs = rt.toArray(); int nbox = boxs.length; for (int ibox=0; ibox<nbox; ++ibox) { boolean removed = rt.remove(boxs[ibox]); assertTrue(removed); } } |
### Question:
Almost implements Serializable, Comparator<Number> { public double reciprocal(final double value) { return divide(1.0, value, 0.0); } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer:
@Test public void testReciprocal() { assertEquals(0.5, a.reciprocal(2.0)); } |
### Question:
Almost implements Serializable, Comparator<Number> { public boolean between(final double x, final double x1, final double x2) { return ((cmp(x, x1) * cmp(x, x2)) <= 0); } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer:
@Test public void testBetween() { assertTrue(a.between(1., 0., 2.)); assertTrue(a.between(-1., 0., -2.)); assertTrue(a.between(-1., -0.5, -2.)); assertTrue(a.between(1., 1.000000000001, 2.)); assertTrue(a.between(-1., -1.000000000001, -2.)); } |
### Question:
Almost implements Serializable, Comparator<Number> { @Override public int compare(final Number n1, final Number n2) { return cmp(n1.doubleValue(), n2.doubleValue()); } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer:
@Test public void testCompare() { assertTrue (a.cmp(1., 0.) > 0); assertTrue (a.cmp(0., 1.) < 0); assertEquals(0,a.cmp(1., 1.)); assertEquals(0,a.cmp(0., 0.)); assertEquals(0,a.cmp(1., 1.000000000001)); Integer i = 1; Integer j = 1; assertEquals(0,a.compare(i,j)); } |
### Question:
Almost implements Serializable, Comparator<Number> { public boolean zero(double r) { if (r < 0.0) { r = -r; } return (r < _minValue); } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer:
@Test public void testZero() { assertTrue (a.zero(0.)); assertTrue (a.zero(a.getMinValue()/2.)); assertFalse(a.zero(a.getMinValue()*2.)); } |
### Question:
Almost implements Serializable, Comparator<Number> { public double getEpsilon() { return _epsilon; } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer:
@Test public void testEpsilon() { assertNotEquals(1.,1.+a.getEpsilon()); assertNotEquals(1.,1.-a.getEpsilon()); } |
### Question:
Almost implements Serializable, Comparator<Number> { public double getMinValue() { return _minValue; } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer:
@Test public void testGetMinValue() { assertNotEquals(0.,a.getMinValue()); assertTrue (a.getMinValue()/2.>0.); } |
### Question:
ArgsParser { public static boolean toBoolean(String s) throws OptionException { s = s.toLowerCase(); if (s.equals("true")) return true; if (s.equals("false")) return false; throw new OptionException("the value "+s+" is not a valid boolean"); } ArgsParser(String[] args, String shortOpts); ArgsParser(String[] args, String shortOpts, String[] longOpts); String[] getOptions(); String[] getValues(); String[] getOtherArgs(); static boolean toBoolean(String s); static double toDouble(String s); static float toFloat(String s); static int toInt(String s); static long toLong(String s); }### Answer:
@Test(expectedExceptions = ArgsParser.OptionException.class) public void testBooleanConverterShouldThrowException() throws Exception { ArgsParser.toBoolean("true"); ArgsParser.toBoolean("Foo"); } |
### Question:
Almost implements Serializable, Comparator<Number> { public boolean equal(final double r1, final double r2) { return (cmp(r1, r2) == 0); } Almost(); Almost(final double epsilon, final double minValue); Almost(final double epsilon); Almost(int significantDigits); Almost(final boolean isDouble); double getEpsilon(); double getMinValue(); boolean between(final double x, final double x1, final double x2); int outside(final double x, final double x1, final double x2); boolean zero(double r); boolean equal(final double r1, final double r2); boolean lt(final double r1, final double r2); boolean le(final double r1, final double r2); boolean gt(final double r1, final double r2); boolean ge(final double r1, final double r2); int cmp(final double r1, final double r2); int hashCodeOf(final Number number, final int significantDigits); int hashCodeOf(final Number number); double divide(final double top, final double bottom, final boolean limitIsOne); double reciprocal(final double value); double divide(double top, double bottom, final double limit); @Override int compare(final Number n1, final Number n2); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); static final Almost FLOAT; static final Almost DOUBLE; }### Answer:
@Test(expectedExceptions = IllegalArgumentException.class) public void testNaNsThrowsException() { Almost.FLOAT.equal(0,Float.NaN); Almost.FLOAT.equal(0,Double.NaN); } |
### Question:
UnitSphereSampling { private static void testSymmetry(UnitSphereSampling uss) { int mi = uss.getMaxIndex(); for (int i=1,j=-i; i<=mi; ++i,j=-i) { float[] p = uss.getPoint(i); float[] q = uss.getPoint(j); assert p[0]==-q[0]; assert p[1]==-q[1]; assert p[2]==-q[2]; } int npoint = 10000; for (int ipoint=0; ipoint<npoint; ++ipoint) { float[] p = randomPoint(); float[] q = {-p[0],-p[1],-p[2]}; int i = uss.getIndex(p); int j = uss.getIndex(q); if (p[2]==0.0f) { assert i+j==mi+1; } else { assert -i==j; } } } UnitSphereSampling(); UnitSphereSampling(int nbits); int countSamples(); int getMaxIndex(); float[] getPoint(int index); int getIndex(float x, float y, float z); int getIndex(float[] xyz); int[] getTriangle(float x, float y, float z); int[] getTriangle(float[] xyz); float[] getWeights(float x, float y, float z, int[] iabc); float[] getWeights(float[] xyz, int[] iabc); static short[] encode16(float[] x, float[] y, float[] z); static short[][] encode16(float[][] x, float[][] y, float[][] z); static short[][][] encode16(
float[][][] x, float[][][] y, float[][][] z); static void main(String[] args); }### Answer:
@Test public void testSymmetry() { testSymmetry(8); testSymmetry(16); } |
### Question:
UnitSphereSampling { private static void testTriangle(UnitSphereSampling uss) { int npoint = 1000000; for (int ipoint=0; ipoint<npoint; ++ipoint) { float[] p = randomPoint(); int i = uss.getIndex(p); int[] abc = uss.getTriangle(p); int ia = abc[0], ib = abc[1], ic = abc[2]; float[] q = uss.getPoint(i); float[] qa = uss.getPoint(ia); float[] qb = uss.getPoint(ib); float[] qc = uss.getPoint(ic); float d = distanceOnSphere(p,q); float da = distanceOnSphere(p,qa); float db = distanceOnSphere(p,qb); float dc = distanceOnSphere(p,qc); if (i!=ia && i!=ib && i!=ic) { trace("d="+d+" da="+da+" db="+db+" dc="+dc); dump(p); dump(q); dump(qa); dump(qb); dump(qc); assert false:"i equals ia or ib or ic"; } } } UnitSphereSampling(); UnitSphereSampling(int nbits); int countSamples(); int getMaxIndex(); float[] getPoint(int index); int getIndex(float x, float y, float z); int getIndex(float[] xyz); int[] getTriangle(float x, float y, float z); int[] getTriangle(float[] xyz); float[] getWeights(float x, float y, float z, int[] iabc); float[] getWeights(float[] xyz, int[] iabc); static short[] encode16(float[] x, float[] y, float[] z); static short[][] encode16(float[][] x, float[][] y, float[][] z); static short[][][] encode16(
float[][][] x, float[][][] y, float[][][] z); static void main(String[] args); }### Answer:
@Test public void testTriangle() { testTriangle(8); testTriangle(16); } |
### Question:
ArgsParser { public static double toDouble(String s) throws OptionException { try { return Double.valueOf(s); } catch (NumberFormatException e) { throw new OptionException("the value "+s+" is not a valid double"); } } ArgsParser(String[] args, String shortOpts); ArgsParser(String[] args, String shortOpts, String[] longOpts); String[] getOptions(); String[] getValues(); String[] getOtherArgs(); static boolean toBoolean(String s); static double toDouble(String s); static float toFloat(String s); static int toInt(String s); static long toLong(String s); }### Answer:
@Test(expectedExceptions = ArgsParser.OptionException.class) public void testDoubleConverterShouldThrowException() throws Exception { ArgsParser.toDouble("1.986"); ArgsParser.toDouble("Foo"); } |
### Question:
ArgsParser { public static float toFloat(String s) throws OptionException { try { return Float.valueOf(s); } catch (NumberFormatException e) { throw new OptionException("the value "+s+" is not a valid float"); } } ArgsParser(String[] args, String shortOpts); ArgsParser(String[] args, String shortOpts, String[] longOpts); String[] getOptions(); String[] getValues(); String[] getOtherArgs(); static boolean toBoolean(String s); static double toDouble(String s); static float toFloat(String s); static int toInt(String s); static long toLong(String s); }### Answer:
@Test(expectedExceptions = ArgsParser.OptionException.class) public void testFloatConverterShouldThrowException() throws Exception { ArgsParser.toFloat("1.986"); ArgsParser.toFloat("Foo"); } |
### Question:
ArgsParser { public static int toInt(String s) throws OptionException { try { return Integer.parseInt(s); } catch (NumberFormatException e) { throw new OptionException("the value "+s+" is not a valid int"); } } ArgsParser(String[] args, String shortOpts); ArgsParser(String[] args, String shortOpts, String[] longOpts); String[] getOptions(); String[] getValues(); String[] getOtherArgs(); static boolean toBoolean(String s); static double toDouble(String s); static float toFloat(String s); static int toInt(String s); static long toLong(String s); }### Answer:
@Test(expectedExceptions = ArgsParser.OptionException.class) public void testIntConverterShouldThrowException() throws Exception { ArgsParser.toInt("1986"); ArgsParser.toInt("Foo"); } |
### Question:
ArgsParser { public static long toLong(String s) throws OptionException { try { return Long.parseLong(s); } catch (NumberFormatException e) { throw new OptionException("the value "+s+" is not a valid long"); } } ArgsParser(String[] args, String shortOpts); ArgsParser(String[] args, String shortOpts, String[] longOpts); String[] getOptions(); String[] getValues(); String[] getOtherArgs(); static boolean toBoolean(String s); static double toDouble(String s); static float toFloat(String s); static int toInt(String s); static long toLong(String s); }### Answer:
@Test(expectedExceptions = ArgsParser.OptionException.class) public void testLongConverterShouldThrowException() throws Exception { ArgsParser.toLong("1986"); ArgsParser.toLong("Foo"); } |
### Question:
BrentZeroFinder { public double findZero(double a, double b, double tol) { double fa = _f.evaluate(a); double fb = _f.evaluate(b); return findZero(a,fa,b,fb,tol); } BrentZeroFinder(Function f); double f(double x); double findZero(double a, double b, double tol); double findZero(
double a, double fa, double b, double fb, double tol); }### Answer:
@Test public void testForsythe() { ZeroFunc1 f1 = new ZeroFunc1(); f1.findZero(2.0,3.0); ZeroFunc2 f2 = new ZeroFunc2(); f2.findZero(-1.0,3.0); ZeroFunc3 f3 = new ZeroFunc3(); f3.findZero(-1.0,3.0); } |
### Question:
BoundingBoxTree { public Node getRoot() { return _root; } BoundingBoxTree(int minSize, float[] xyz); BoundingBoxTree(int minSize, float[] x, float[] y, float[] z); Node getRoot(); }### Answer:
@Test public void testRandom() { int minSize = 10; int n = 10000; float[] x = randfloat(n); float[] y = randfloat(n); float[] z = randfloat(n); BoundingBoxTree bbt = new BoundingBoxTree(minSize,x,y,z); BoundingBoxTree.Node root = bbt.getRoot(); test(root,minSize,x,y,z); } |
### Question:
DMatrixChd { public double det() { return _det; } DMatrixChd(DMatrix a); boolean isPositiveDefinite(); DMatrix getL(); double det(); DMatrix solve(DMatrix b); }### Answer:
@Test public void testSimple() { DMatrix a = new DMatrix(new double[][]{ {1.0, 1.0}, {1.0, 4.0}, }); test(a); DMatrixChd chd = new DMatrixChd(a); assertEqualFuzzy(3.0,chd.det()); } |
### Question:
DMatrixLud { public double det() { Check.argument(_m==_n,"A is square"); return _det; } DMatrixLud(DMatrix a); boolean isSingular(); DMatrix getL(); DMatrix getU(); DMatrix getP(); int[] getPivotIndices(); double det(); DMatrix solve(DMatrix b); }### Answer:
@Test public void testSimple() { DMatrix a = new DMatrix(new double[][]{ {0.0, 2.0}, {3.0, 4.0}, }); test(a); DMatrixLud lud = new DMatrixLud(a); assertEqualFuzzy(-6.0,lud.det()); } |
### Question:
DMatrixQrd { public boolean isFullRank() { for (int j=0; j<_n; ++j) { if (_qr[j+j*_m]==0.0) return false; } return true; } DMatrixQrd(DMatrix a); boolean isFullRank(); DMatrix getQ(); DMatrix getR(); DMatrix solve(DMatrix b); }### Answer:
@Test public void testRankDeficient() { DMatrix a = new DMatrix(new double[][]{ {0.0, 0.0}, {3.0, 4.0}, }); DMatrixQrd qrd = new DMatrixQrd(a); assertFalse(qrd.isFullRank()); } |
### Question:
DMatrixSvd { public double cond() { return _s[0]/_s[_mn-1]; } DMatrixSvd(DMatrix a); DMatrix getU(); DMatrix getS(); double[] getSingularValues(); DMatrix getV(); DMatrix getVTranspose(); double norm2(); double cond(); int rank(); }### Answer:
@Test public void testCond() { DMatrix a = new DMatrix(new double[][]{ {1.0, 3.0}, {7.0, 9.0}, }); int m = a.getM(); int n = a.getN(); DMatrixSvd svd = new DMatrixSvd(a); double[] s = svd.getSingularValues(); double smax = max(s); assertEqualExact(s[0],smax); double smin = min(s); assertEqualExact(s[min(m,n)-1],smin); double cond = svd.cond(); assertEqualExact(smax/smin,cond); } |
### Question:
ArgsParser { public ArgsParser(String[] args, String shortOpts) throws OptionException { _args = args; _shortOpts = shortOpts; _longOpts = new String[0]; init(); } ArgsParser(String[] args, String shortOpts); ArgsParser(String[] args, String shortOpts, String[] longOpts); String[] getOptions(); String[] getValues(); String[] getOtherArgs(); static boolean toBoolean(String s); static double toDouble(String s); static float toFloat(String s); static int toInt(String s); static long toLong(String s); }### Answer:
@Test public void testArgsParser() { String[][] args = { {"-a3.14","-b","foo"}, {"-a","3.14","-b","foo"}, {"--alpha","3.14","--beta","foo"}, {"--a=3.14","--b","foo"}, {"--a=3.14","--b","foo"}, }; for (String[] arg:args) { float a = 0.0f; boolean b = false; try { String shortOpts = "ha:b"; String[] longOpts = {"help","alpha=","beta"}; ArgsParser ap = new ArgsParser(arg,shortOpts,longOpts); String[] opts = ap.getOptions(); String[] vals = ap.getValues(); for (int i=0; i<opts.length; ++i) { String opt = opts[i]; String val = vals[i]; if (opt.equals("-h") || opt.equals("--help")) { assertTrue(false); } else if (opt.equals("-a") || opt.equals("--alpha")) { a = ArgsParser.toFloat(val); } else if (opt.equals("-b") || opt.equals("--beta")) { b = true; } } String[] otherArgs = ap.getOtherArgs(); assertTrue(otherArgs.length==1); assertTrue(otherArgs[0].equals("foo")); assertTrue(a==3.14f); assertTrue(b); } catch (ArgsParser.OptionException e) { assertTrue("no exceptions: e="+e.getMessage(),false); } } } |
### Question:
DataSetParametersList { public static DataSetParametersList fromXML(String dataDefinition) throws SourceBeanException { return new DataSetParametersList(dataDefinition); } DataSetParametersList(); DataSetParametersList(String dataDefinition); void loadFromXML(String dataDefinition); String toXML(); String getDataSetResult(IEngUserProfile profile); List getProfileAttributeNames(); boolean requireProfileAttributes(); void add(String name, String type); void add(String name, String type, String defaultValue); void remove(String name, String type); static DataSetParametersList fromXML(String dataDefinition); List getItems(); void setPars(List items); static final String DEFAULT_VALUE_XML; }### Answer:
@Test public void testFromXML() throws SourceBeanException { DataSetParametersList fromXML = DataSetParametersList.fromXML(XML); checkParams(fromXML); } |
### Question:
ParametersDecoder { public boolean isMultiValues(String value) { return value.trim().matches(multiValueRegex); } ParametersDecoder(); ParametersDecoder(String openBlockMarker, String closeBlockMarker); String getCloseBlockMarker(); void setCloseBlockMarker(String closeBlockMarker); String getOpenBlockMarker(); void setOpenBlockMarker(String openBlockMarker); boolean isMultiValues(String value); String decodeParameter(Object paramaterValue); List decode(String value); List getOriginalValues(String value); static HashMap getDecodedRequestParameters(HttpServletRequest servletRequest); static HashMap getDecodedRequestParameters(IContainer requestContainer); static void main(String[] args); static final String DEFAULT_OPEN_BLOCK_MARKER; static final String DEFAULT_CLOSE_BLOCK_MARKER; }### Answer:
@Test public void testIsMultiValue() { ParametersDecoder decoder = new ParametersDecoder(); String value = "{;{American;Colony;Ebony;Johnson;Urban}STRING}"; boolean isMultiValue = decoder.isMultiValues(value); assertTrue(isMultiValue); String json = "{name: {a : 4, b : 4}}"; isMultiValue = decoder.isMultiValues(json); assertTrue(!isMultiValue); } |
### Question:
SimpleRestClient { protected Response executeGetService(Map<String, Object> parameters, String serviceUrl, String userId) throws Exception { return executeService(parameters, serviceUrl, userId, RequestTypeEnum.GET, null, null); } SimpleRestClient(String hmacKey); SimpleRestClient(); boolean isAddServerUrl(); void setAddServerUrl(boolean addServerUrl); }### Answer:
@Test public void testExecuteGetService() throws Exception { SimpleRestClient client = getSimpleRestClient(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("a", "b"); parameters.put("c", "d"); Response resp = client.executeGetService(parameters, "http: Assert.assertEquals(200, resp.getStatus()); Assert.assertTrue(DummyServlet.arrived); }
@Test public void testExecuteGetServiceFail() throws Exception { SimpleRestClient client = getSimpleRestClientFail(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("a", "b"); parameters.put("c", "d"); boolean done = false; try { client.executeGetService(parameters, "http: } catch (Exception e) { done = true; } Assert.assertTrue(done); Assert.assertFalse(DummyServlet.arrived); } |
### Question:
SimpleRestClient { protected Response executePostService(Map<String, Object> parameters, String serviceUrl, String userId, String mediaType, Object data) throws Exception { return executeService(parameters, serviceUrl, userId, RequestTypeEnum.POST, mediaType, data); } SimpleRestClient(String hmacKey); SimpleRestClient(); boolean isAddServerUrl(); void setAddServerUrl(boolean addServerUrl); }### Answer:
@Test public void testExecutePostService() throws Exception { SimpleRestClient client = getSimpleRestClient(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("a", "b"); parameters.put("c", "d"); Response resp = client.executePostService(parameters, "http: Assert.assertEquals(200, resp.getStatus()); Assert.assertTrue(DummyServlet.arrived); }
@Test public void testExecutePostServiceFail() throws Exception { SimpleRestClient client = getSimpleRestClientFail(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("a", "b"); parameters.put("c", "d"); boolean done = false; try { client.executePostService(parameters, "http: } catch (Exception e) { done = true; } Assert.assertTrue(done); Assert.assertFalse(DummyServlet.arrived); } |
### Question:
RealtimeEvaluationStrategy extends CachedEvaluationStrategy { @Override protected DatasetEvaluationStrategyType getEvaluationStrategy() { return DatasetEvaluationStrategyType.REALTIME; } RealtimeEvaluationStrategy(UserProfile userProfile, IDataSet dataSet, ICache cache); }### Answer:
@Test public void shouldReturnRealtimeStrategyType() { RealtimeEvaluationStrategy strategy = (RealtimeEvaluationStrategy) DatasetEvaluationStrategyFactory.get(DatasetEvaluationStrategyType.REALTIME, new MockDataSet(), new UserProfile()); assertThat(strategy.getEvaluationStrategy(), is(DatasetEvaluationStrategyType.REALTIME)); } |
### Question:
PersistedEvaluationStrategy extends AbstractJdbcEvaluationStrategy { @Override protected String getTableName() { return dataSet.getPersistTableName(); } PersistedEvaluationStrategy(IDataSet dataSet); }### Answer:
@Test public void shouldUsePersistedTableName() { final String TABLE_NAME = "PersistedTable"; MockDataSet dataSet = new MockDataSet(); dataSet.setPersistTableName(TABLE_NAME); PersistedEvaluationStrategy strategy = (PersistedEvaluationStrategy) DatasetEvaluationStrategyFactory.get(DatasetEvaluationStrategyType.PERSISTED, dataSet, new UserProfile()); Assert.assertThat(strategy.getTableName(), is(TABLE_NAME)); } |
### Question:
PersistedEvaluationStrategy extends AbstractJdbcEvaluationStrategy { @Override protected IDataSource getDataSource() { return dataSet.getDataSourceForWriting(); } PersistedEvaluationStrategy(IDataSet dataSet); }### Answer:
@Test public void shouldUseDatasourceForWriting() { final String DATASOURCE_LABEL = "DatasourceForWriting"; MockDataSet dataSet = new MockDataSet(); IDataSource dataSource = DataSourceFactory.getDataSource(); dataSource.setLabel(DATASOURCE_LABEL); dataSet.setDataSourceForWriting(dataSource); PersistedEvaluationStrategy strategy = (PersistedEvaluationStrategy) DatasetEvaluationStrategyFactory.get(DatasetEvaluationStrategyType.PERSISTED, dataSet, new UserProfile()); Assert.assertThat(strategy.getDataSource().getLabel(), is(DATASOURCE_LABEL)); } |
### Question:
PersistedEvaluationStrategy extends AbstractJdbcEvaluationStrategy { @Override protected Date getDate() { Date toReturn = null; Trigger trigger = loadTrigger(); Date previousFireTime = null; if (trigger != null) { previousFireTime = trigger.getPreviousFireTime(); } if (previousFireTime != null) { toReturn = previousFireTime; } else { toReturn = dataSet.getDateIn(); } return toReturn; } PersistedEvaluationStrategy(IDataSet dataSet); }### Answer:
@Test public void shouldUsePreviousFireTimeToSetDataStoreDate() { final Date now = new Date(); new MockUp<PersistedEvaluationStrategy>() { @Mock private Trigger loadTrigger() { Trigger trigger = new Trigger(); trigger.setPreviousFireTime(now); return trigger; } }; PersistedEvaluationStrategy strategy = (PersistedEvaluationStrategy) DatasetEvaluationStrategyFactory.get(DatasetEvaluationStrategyType.PERSISTED, new MockDataSet(), new UserProfile()); Assert.assertThat(strategy.getDate(), is(now)); }
@Test public void shouldUseDatasetDateInToSetDataStoreDate() { final Date now = new Date(); new MockUp<PersistedEvaluationStrategy>() { @Mock private Trigger loadTrigger() { return new Trigger(); } }; MockDataSet dataSet = new MockDataSet(); dataSet.setDateIn(now); PersistedEvaluationStrategy strategy = (PersistedEvaluationStrategy) DatasetEvaluationStrategyFactory.get(DatasetEvaluationStrategyType.PERSISTED, dataSet, new UserProfile()); Assert.assertThat(strategy.getDate(), is(now)); } |
### Question:
CachedEvaluationStrategy extends AbstractEvaluationStrategy { protected DatasetEvaluationStrategyType getEvaluationStrategy() { return DatasetEvaluationStrategyType.CACHED; } CachedEvaluationStrategy(UserProfile userProfile, IDataSet dataSet, ICache cache); }### Answer:
@Test public void shouldReturnCachedStrategyType() { CachedEvaluationStrategy strategy = (CachedEvaluationStrategy) DatasetEvaluationStrategyFactory.get(DatasetEvaluationStrategyType.CACHED, new MockDataSet(), new UserProfile()); assertThat(strategy.getEvaluationStrategy(), is(DatasetEvaluationStrategyType.CACHED)); } |
### Question:
LabeledEdge extends DefaultEdge { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LabeledEdge other = (LabeledEdge) obj; if (label == null) { if (other.label != null) return false; } else if (!label.equals(other.label)) return false; if (source == null && other.source != null) return false; if (target == null && other.target != null) return false; return (source.equals(other.source) && target.equals(other.target)) || (source.equals(other.target) && target.equals(other.source)); } LabeledEdge(V source, V target, String label); @Override V getSource(); @Override V getTarget(); String getLabel(); boolean isParametric(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testEquals() { assertEquals(new LabeledEdge<String>("x", "y", "label"), new LabeledEdge<String>("x", "y", "label")); assertEquals(new LabeledEdge<String>("x", "y", "label"), new LabeledEdge<String>("y", "x", "label")); assertNotEquals(new LabeledEdge<String>("x", "y", "label"), new LabeledEdge<String>("z", "y", "label")); assertNotEquals(new LabeledEdge<String>("x", "y", "label"), new LabeledEdge<String>("x", "z", "label")); assertNotEquals(new LabeledEdge<String>("x", "y", "label"), new LabeledEdge<String>("x", "z", "tag")); } |
### Question:
EdgeGroup { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof EdgeGroup)) return false; EdgeGroup other = (EdgeGroup) obj; if (orderedEdgeNames == null) { if (other.orderedEdgeNames != null) return false; } else if (!orderedEdgeNames.equals(other.orderedEdgeNames)) return false; if (edgeNames == null) { if (other.edgeNames != null) return false; } else if (!edgeNames.equals(other.edgeNames)) return false; return true; } EdgeGroup(Set<LabeledEdge<String>> edges); Set<String> getEdgeNames(); String getOrderedEdgeNames(); Set<Tuple> getValues(); void addValues(Set<Tuple> values); void addValue(Tuple value); boolean isResolved(); void resolve(); void unresolve(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testEquals() { assertEquals(eg1, eg1); assertEquals(eg1, eg2); assertNotEquals(eg1, eg3); } |
### Question:
EdgeGroup { public String getOrderedEdgeNames() { return orderedEdgeNames; } EdgeGroup(Set<LabeledEdge<String>> edges); Set<String> getEdgeNames(); String getOrderedEdgeNames(); Set<Tuple> getValues(); void addValues(Set<Tuple> values); void addValue(Tuple value); boolean isResolved(); void resolve(); void unresolve(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testGetColumnNames() { assertEquals(eg1.getOrderedEdgeNames(), eg1.getOrderedEdgeNames()); assertEquals(eg1.getOrderedEdgeNames(), eg4.getOrderedEdgeNames()); } |
### Question:
DataSetParametersList { public void loadFromXML(String dataDefinition) throws SourceBeanException { logger.debug("IN"); dataDefinition.trim(); InputSource stream = new InputSource(new StringReader(dataDefinition)); SourceBean source = SourceBean.fromXMLStream(stream); if (!source.getName().equals("PARAMETERSLIST")) { SourceBean wrapper = new SourceBean("PARAMETERSLIST"); wrapper.setAttribute(source); source = wrapper; } List listRows = source.getAttributeAsList("ROWS.ROW"); Iterator iterRows = listRows.iterator(); ArrayList parsList = new ArrayList(); while (iterRows.hasNext()) { DataSetParameterItem par = new DataSetParameterItem(); SourceBean element = (SourceBean) iterRows.next(); String name = (String) element.getAttribute("NAME"); par.setName(name); String type = (String) element.getAttribute("TYPE"); par.setType(type); String defaultValue = (String) element.getAttribute(DEFAULT_VALUE_XML); par.setDefaultValue(defaultValue); parsList.add(par); } setPars(parsList); logger.debug("OUT"); } DataSetParametersList(); DataSetParametersList(String dataDefinition); void loadFromXML(String dataDefinition); String toXML(); String getDataSetResult(IEngUserProfile profile); List getProfileAttributeNames(); boolean requireProfileAttributes(); void add(String name, String type); void add(String name, String type, String defaultValue); void remove(String name, String type); static DataSetParametersList fromXML(String dataDefinition); List getItems(); void setPars(List items); static final String DEFAULT_VALUE_XML; }### Answer:
@Test public void testLoadFromXML() throws SourceBeanException { DataSetParametersList dspl = new DataSetParametersList(); dspl.loadFromXML(XML); checkParams(dspl); } |
### Question:
ExceptionUtilities { public static String getStackTraceAsString( Exception aException ){ String vStackTrace = "\t" + aException.toString() + "\n"; for( StackTraceElement vElement : aException.getStackTrace() ){ vStackTrace += "\t\t" + vElement.toString() + "\n"; } return vStackTrace; } static String getStackTraceAsString( Exception aException ); }### Answer:
@Test public void testGetStackTraceAsString() { Exception mockException = mock(Exception.class); when(mockException.toString()).thenReturn("Mocked Exception"); when(mockException.getStackTrace()).thenReturn(new StackTraceElement[]{ new StackTraceElement("String","toString()","testfile",123), new StackTraceElement("Testclass","testMethod()","testfile2",42) }); String expectedResult = "\tMocked Exception\n" + "\t\tString.toString()(testfile:123)\n" + "\t\tTestclass.testMethod()(testfile2:42)\n"; assertThat(ExceptionUtilities.getStackTraceAsString(mockException)).isEqualTo(expectedResult); } |
### Question:
ToServerManagement extends Thread { public static ToServerManagement getInstance() { if( ToServerManagement.sINSTANCE == null){ ToServerManagement.sINSTANCE = new ToServerManagement(); } return ToServerManagement.sINSTANCE; } ToServerManagement(); static ToServerManagement getInstance(); void close(); void resumeManagement(); boolean isSuspended(); void suspendManagement(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isSendingMessages(); }### Answer:
@Test public void testGetInstance() { ToServerManagement vSaveToCompare = ToServerManagement.getInstance(); assertThat(vSaveToCompare).isInstanceOf(ToServerManagement.class); assertThat(vSaveToCompare).isEqualTo(ToServerManagement.getInstance()); } |
### Question:
ToServerManagement extends Thread { public void stopManagement(){ synchronized (this) { mManageMessagesToServer = false; } if( isAlive()){ resumeManagement(); while(isAlive()){ try { Thread.sleep( 10 ); } catch ( Exception vException ) { Core.getLogger().error( "Error stopping ToServerManagement.", vException ); } } Core.getLogger().info( "ToServerManagement stopped." ); } } ToServerManagement(); static ToServerManagement getInstance(); void close(); void resumeManagement(); boolean isSuspended(); void suspendManagement(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isSendingMessages(); }### Answer:
@Test public void testStopManagementWhenNotAlive() { assertThat(mSUT.isAlive()).isFalse(); mSUT.stopManagement(); assertThat(mSUT.isAlive()).isFalse(); verify(mLoggerMock, never()).info("ToServerManagement stopped."); } |
### Question:
ToServerManagement extends Thread { public boolean isSendingMessages(){ return isAlive() && (System.currentTimeMillis() - mLastSendMessage.get() ) < 100; } ToServerManagement(); static ToServerManagement getInstance(); void close(); void resumeManagement(); boolean isSuspended(); void suspendManagement(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isSendingMessages(); }### Answer:
@Test public void testIsSendingMessagesWhenNotAlive() { assertThat(mSUT.isAlive()).isFalse(); assertThat(mSUT.isSendingMessages()).isFalse(); } |
### Question:
Movement implements Action { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Movement other = (Movement) obj; if (mLeftWheelVelocity != other.mLeftWheelVelocity) return false; if (mRightWheelVelocity != other.mRightWheelVelocity) return false; return true; } Movement( int aRightWheelVelocity, int aLeftWheelVelocity ); int getmRightWheelVelocity(); int getmLeftWheelVelocity(); @Override String getXMLString(); @Override int hashCode(); @Override boolean equals(Object obj); static final Movement NO_MOVEMENT; }### Answer:
@Test public void testEqualsWithDifferentRightWheelVelocity() { Movement movement1 = new Movement(51,50); Movement movement2 = new Movement(49,50); assertThat(movement1.equals(movement2)).isEqualTo(false); }
@Test public void testEqualsWithSameValues() { Movement movement1 = new Movement(50,50); Movement movement2 = new Movement(50,50); assertThat(movement1.equals(movement2)).isEqualTo(true); }
@Test public void testEqualsWithSameObject() { Movement movement = new Movement(51,50); assertThat(movement.equals(movement)).isEqualTo(true); }
@Test public void testEqualsWithObjectIsNull() { Movement movement = new Movement(51,50); assertThat(movement.equals(null)).isEqualTo(false); }
@Test public void testEqualsWithDifferentClass() { Movement movement = new Movement(51,50); assertThat(movement.equals(new Integer(12))).isEqualTo(false); }
@Test public void testEqualsWithDifferentLeftWheelVelocity() { Movement movement1 = new Movement(51,50); Movement movement2 = new Movement(51,49); assertThat(movement1.equals(movement2)).isEqualTo(false); } |
### Question:
FellowPlayer extends ReferencePoint { @Override void setPointName( ReferencePointName aPointName ) { super.setPointName( ReferencePointName.Player ); mId = IDCOUNTER++; } FellowPlayer(); FellowPlayer(int aId, String aNickname, Boolean aStatus, double aDistanceToPlayer, double aAngleToPlayer, double aOrientation); @XmlElement(name="id") int getId(); @XmlTransient String getNickname(); @XmlTransient Boolean getStatus(); @XmlTransient double getDistanceToPlayer(); @XmlTransient double getAngleToPlayer(); @XmlTransient double getOrientation(); @Override String toString(); @Override boolean equals(Object obj); }### Answer:
@Test public void setPointNameText() { FellowPlayer fellowPlayer = new FellowPlayer(); int IDCountBefore = FellowPlayer.IDCOUNTER ; fellowPlayer.setPointName(ReferencePointName.Ball); int IDCountAfter = FellowPlayer.IDCOUNTER; assert(IDCountBefore+1==IDCountAfter); } |
### Question:
ReferencePoint { public void setXOfPoint( double aXValue ) { mX = aXValue; set( mX, mY, false ); } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testSetXOfPoint() { ReferencePoint referencePoint = new ReferencePoint(); referencePoint.setXOfPoint(10); assertThat(referencePoint.getXOfPoint()).isCloseTo(10, Percentage.withPercentage(1)); } |
### Question:
ReferencePoint { public void setYOfPoint( double aYValue ) { mY = aYValue; set( mX, mY, false ); } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testSetYOfPoint() { ReferencePoint referencePoint = new ReferencePoint(); referencePoint.setYOfPoint(10); assertThat(referencePoint.getYOfPoint()).isCloseTo(10, Percentage.withPercentage(1)); } |
### Question:
ReferencePoint { public ReferencePoint copy () { return new ReferencePoint( this ); } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testCopy() { ReferencePoint referencePoint = new ReferencePoint(10,15,false); ReferencePoint copyOfReferencePoint = referencePoint.copy(); assertThat(copyOfReferencePoint).isNotNull(); assertThat(copyOfReferencePoint).isInstanceOf(ReferencePoint.class); assertThat(copyOfReferencePoint.getXOfPoint()).isCloseTo(10, Percentage.withPercentage(1)); assertThat(copyOfReferencePoint.getYOfPoint()).isCloseTo(15, Percentage.withPercentage(1)); } |
### Question:
ReferencePoint { public ReferencePoint add( ReferencePoint aReferencePoint ) { mX += aReferencePoint.mX; mY += aReferencePoint.mY; return set( mX, mY, false ); } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testAdd() { ReferencePoint referencePoint = new ReferencePoint(50,20,false); ReferencePoint plusReferencePoint = new ReferencePoint(10,10, false); referencePoint.add(plusReferencePoint); assertThat(referencePoint.getXOfPoint()).isCloseTo(60,Percentage.withPercentage(1)); assertThat(referencePoint.getYOfPoint()).isCloseTo(30, Percentage.withPercentage(1)); } |
### Question:
ReferencePoint { public ReferencePoint multiply( double scalar ) { mX *= scalar; mY *= scalar; return set( mX, mY, false ); } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testMultiply() { ReferencePoint referencePoint = new ReferencePoint(50,20, false); referencePoint.multiply(2.0); assertThat(referencePoint.getXOfPoint()).isCloseTo(100, Percentage.withPercentage(1)); assertThat(referencePoint.getYOfPoint()).isCloseTo(40,Percentage.withPercentage(1)); } |
### Question:
Kick implements Action { @Override public String getXMLString() { return "<command> <kick> <angle>" + mAngle + "</angle> <force>" + mForce + "</force> </kick> </command>"; } Kick( double aAngle, float aForce); @Override String getXMLString(); double getAngle(); float getForce(); }### Answer:
@Test public void getXMLString() throws Exception { Kick kick = new Kick(90.1, (float) 21.0); assertThat(kick.getXMLString()).isEqualTo("<command> <kick> <angle>90.1</angle> <force>21.0</force> </kick> </command>"); } |
### Question:
Movement implements Action { @Override public String getXMLString() { return "<command> <wheel_velocities> <right>" + mRightWheelVelocity + "</right> <left>" + mLeftWheelVelocity + "</left> </wheel_velocities> </command>"; } Movement( int aRightWheelVelocity, int aLeftWheelVelocity ); int getmRightWheelVelocity(); int getmLeftWheelVelocity(); @Override String getXMLString(); @Override int hashCode(); @Override boolean equals(Object obj); static final Movement NO_MOVEMENT; }### Answer:
@Test public void testGetXMLString() { Movement movement = new Movement(51,50); assertThat(movement.getXMLString()).isEqualTo("<command> <wheel_velocities> <right>51</right> <left>50</left> </wheel_velocities> </command>"); } |
### Question:
ObjectFactory { public RawWorldData createRawWorldData() { return new RawWorldData(); } RawWorldData createRawWorldData(); }### Answer:
@Test public void testCreateRawWorldData() { ObjectFactory objectFactory = new ObjectFactory(); assertThat(objectFactory.createRawWorldData()).isInstanceOf(RawWorldData.class); } |
### Question:
InitialConnectionData implements Action { public InitialConnectionData( BotInformation aBot ){ mConnection.type = "Client"; mConnection.protocol_version = 1.0; mConnection.nickname = aBot.getBotname(); mConnection.rc_id = aBot.getRcId(); mConnection.vt_id = aBot.getVtId(); } InitialConnectionData( BotInformation aBot ); @Override String getXMLString(); }### Answer:
@Test public void testInitialConnectionData() { fail("Not yet implemented"); } |
### Question:
InitialConnectionData implements Action { @Override public String getXMLString() { StringWriter vXMLDataStream = new StringWriter(); JAXB.marshal( mConnection, vXMLDataStream ); String vXMLDataString = vXMLDataStream.toString(); vXMLDataString = vXMLDataString.substring( vXMLDataString.indexOf('>') + 2 ); return vXMLDataString; } InitialConnectionData( BotInformation aBot ); @Override String getXMLString(); }### Answer:
@Test public void testGetXMLString() { InitialConnectionData initialConnectionData = new InitialConnectionData(botInformationMock); fail("Not yet implemented"); } |
### Question:
NetworkCommunication { public void sendDatagramm( String aData ) throws IOException { mDataPaket.setData( aData.getBytes() ); mToServerSocket.send( mDataPaket ); } NetworkCommunication( InetAddress aServerAddress, int aServerPort ); NetworkCommunication( InetAddress aServerAddress, int aServerPort, int aClientPort); void sendDatagramm( String aData ); String getDatagramm( int aWaitTime ); void closeConnection(); boolean isConnected(); DatagramPacket getDataPaket(); DatagramSocket getToServerSocket(); void setToServerSocket(DatagramSocket mToServerSocket); void setDataPaket(DatagramPacket mDataPaket); String toString(); }### Answer:
@Test public void testSendDatagramm() { } |
### Question:
Movement implements Action { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mLeftWheelVelocity; result = prime * result + mRightWheelVelocity; return result; } Movement( int aRightWheelVelocity, int aLeftWheelVelocity ); int getmRightWheelVelocity(); int getmLeftWheelVelocity(); @Override String getXMLString(); @Override int hashCode(); @Override boolean equals(Object obj); static final Movement NO_MOVEMENT; }### Answer:
@Test public void testHashCode() { Movement movement = new Movement(51,50); assertThat(movement.hashCode()).isEqualTo(2562); } |
### Question:
Core { synchronized public BotInformation getBotinformation() { Core.getLogger().debug( "Retriving Botinformation: \n" + mBotinformation.toString() ); return mBotinformation; } Core(); Core( BotInformation aBotInformation ); static Core getInstance(); static synchronized Logger getLogger(); void close(); void startBot( String[] aCommandline ); @SuppressWarnings("resource") boolean initializeAI(); void disposeAI(); synchronized boolean resumeAI(); synchronized void suspendAI(); boolean startServerConnection( int aNumberOfTries ); void stopServerConnection(); void startServermanagements(); void stopServermanagements(); void resumeServermanagements(); void suspendServermanagements(); synchronized BotInformation getBotinformation(); synchronized void setBotinformation( BotInformation aBotinformation ); synchronized NetworkCommunication getServerConnection(); synchronized ArtificialIntelligence getAI(); }### Answer:
@Test public void testConstructorWithBotInformation() { mSUT = new Core(mBotInformationMock); assertThat(mSUT.getBotinformation()).isEqualTo(mBotInformationMock); } |
### Question:
Core { public static Core getInstance() { if( Core.sINSTANCE == null){ Core.getLogger().trace( "Creating Core-instance." ); Core.sINSTANCE = new Core(); } Core.getLogger().trace( "Retrieving Core-instance." ); return Core.sINSTANCE; } Core(); Core( BotInformation aBotInformation ); static Core getInstance(); static synchronized Logger getLogger(); void close(); void startBot( String[] aCommandline ); @SuppressWarnings("resource") boolean initializeAI(); void disposeAI(); synchronized boolean resumeAI(); synchronized void suspendAI(); boolean startServerConnection( int aNumberOfTries ); void stopServerConnection(); void startServermanagements(); void stopServermanagements(); void resumeServermanagements(); void suspendServermanagements(); synchronized BotInformation getBotinformation(); synchronized void setBotinformation( BotInformation aBotinformation ); synchronized NetworkCommunication getServerConnection(); synchronized ArtificialIntelligence getAI(); }### Answer:
@Test public void testGetInstance() { mSUT = Core.getInstance(); assertThat(mSUT).isInstanceOf(Core.class); assertThat(mSUT).isEqualTo(Core.getInstance()); assertThat(mSUT.getBotinformation()).isEqualTo(Core.getInstance().getBotinformation()); } |
### Question:
Core { public static synchronized Logger getLogger(){ return sBOTCORELOGGER; } Core(); Core( BotInformation aBotInformation ); static Core getInstance(); static synchronized Logger getLogger(); void close(); void startBot( String[] aCommandline ); @SuppressWarnings("resource") boolean initializeAI(); void disposeAI(); synchronized boolean resumeAI(); synchronized void suspendAI(); boolean startServerConnection( int aNumberOfTries ); void stopServerConnection(); void startServermanagements(); void stopServermanagements(); void resumeServermanagements(); void suspendServermanagements(); synchronized BotInformation getBotinformation(); synchronized void setBotinformation( BotInformation aBotinformation ); synchronized NetworkCommunication getServerConnection(); synchronized ArtificialIntelligence getAI(); }### Answer:
@Test public void testGetLogger() { Logger vLoggerToTest = Core.getLogger(); assertThat(vLoggerToTest).isInstanceOf(Logger.class); assertThat(vLoggerToTest).isEqualTo(Core.getLogger()); } |
### Question:
FromServerManagement extends Thread { @Override public void start(){ startManagement(); } FromServerManagement(); static FromServerManagement getInstance(); void close(); void resumeManagement(); void suspendManagement(); boolean isSuspended(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isReceivingMessages(); }### Answer:
@Test public void testStartWithoutNetworkConnection() { when(mCoreMock.getServerConnection()).thenReturn( null ); try{ mSUT.start(); fail("Expected Nullpointerexception"); } catch( Exception vExpectedException ) { assertThat(vExpectedException).isInstanceOf(NullPointerException.class); assertThat(vExpectedException.getMessage()).isEqualToIgnoringCase( "NetworkCommunication cannot be NULL when starting FromServerManagement." ); } }
@Test public void testStartWithNetworkConnectionAndNotAlive() { when(mCoreMock.getServerConnection()).thenReturn( mNetworkCommunicationMock ); when(mCoreMock.getAI()).thenReturn( null ); mSUT.start(); assertThat(mSUT.isAlive()).isTrue(); verify(mLoggerMock).info("FromServerManagement started."); } |
### Question:
FromServerManagement extends Thread { public static FromServerManagement getInstance() { if( FromServerManagement.sINSTANCE == null){ FromServerManagement.sINSTANCE = new FromServerManagement(); } return FromServerManagement.sINSTANCE; } FromServerManagement(); static FromServerManagement getInstance(); void close(); void resumeManagement(); void suspendManagement(); boolean isSuspended(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isReceivingMessages(); }### Answer:
@Test public void testGetInstance() { FromServerManagement vSaveToCompare = FromServerManagement.getInstance(); assertThat(vSaveToCompare).isInstanceOf(FromServerManagement.class); assertThat(vSaveToCompare).isEqualTo(FromServerManagement.getInstance()); } |
### Question:
FromServerManagement extends Thread { public void stopManagement(){ synchronized (this) { mManageMessagesFromServer = false; } if( isAlive()){ mSuspended = false; while(isAlive()){ try { Thread.sleep( 10 ); } catch ( Exception vException ) { Core.getLogger().error( "Error stopping FromServerManagement.", vException ); } } Core.getLogger().info( "FromServerManagement stopped." ); } } FromServerManagement(); static FromServerManagement getInstance(); void close(); void resumeManagement(); void suspendManagement(); boolean isSuspended(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isReceivingMessages(); }### Answer:
@Test public void testStopManagementWhenNotAlive() { assertThat(mSUT.isAlive()).isFalse(); mSUT.stopManagement(); assertThat(mSUT.isAlive()).isFalse(); verify(mLoggerMock, never()).info("FromServerManagement stopped."); } |
### Question:
FromServerManagement extends Thread { public boolean isReceivingMessages(){ return isAlive() && (System.currentTimeMillis() - mLastReceivedMessage.get()) < 100; } FromServerManagement(); static FromServerManagement getInstance(); void close(); void resumeManagement(); void suspendManagement(); boolean isSuspended(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isReceivingMessages(); }### Answer:
@Test public void testIsReceivingMessagesWhenNotAlive() { assertThat(mSUT.isAlive()).isFalse(); assertThat(mSUT.isReceivingMessages()).isFalse(); } |
### Question:
ReloadAiManagement extends Thread { @Override public void start(){ startManagement(); } ReloadAiManagement(); static ReloadAiManagement getInstance(); void close(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); }### Answer:
@Test public void testStartWhileNotAlive() { when(mCoreMock.getAI()).thenReturn( null ); assertThat(mSUT.isAlive()).isFalse(); mSUT.start(); assertThat(mSUT.isAlive()).isTrue(); verify(mLoggerMock).info("RestartAiServerManagement started."); }
@Test public void testStartWhileAlive() { when(mCoreMock.getAI()).thenReturn( null ); mSUT.start(); assertThat(mSUT.isAlive()).isTrue(); mSUT.start(); assertThat(mSUT.isAlive()).isTrue(); verify(mLoggerMock, times(1)).info("RestartAiServerManagement started."); } |
### Question:
ReloadAiManagement extends Thread { public static ReloadAiManagement getInstance() { if( ReloadAiManagement.sINSTANCE == null){ ReloadAiManagement.sINSTANCE = new ReloadAiManagement(); } return ReloadAiManagement.sINSTANCE; } ReloadAiManagement(); static ReloadAiManagement getInstance(); void close(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); }### Answer:
@Test public void testGetInstance() { ReloadAiManagement vSaveToCompare = ReloadAiManagement.getInstance(); assertThat(vSaveToCompare).isInstanceOf(ReloadAiManagement.class); assertThat(vSaveToCompare).isEqualTo(ReloadAiManagement.getInstance()); } |
### Question:
ReloadAiManagement extends Thread { public void stopManagement(){ mAiActive = false; if( isAlive()){ Core.getLogger().info( "RestartAiServerManagement stopping." ); while(isAlive()){ try { Thread.sleep( 10 ); } catch ( Exception vException ) { Core.getLogger().error( "Error stopping RestartAiServerManagement.", vException ); } } Core.getLogger().info( "RestartAiServerManagement stopped." ); } } ReloadAiManagement(); static ReloadAiManagement getInstance(); void close(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); }### Answer:
@Test public void testStopManagementWhenNotAlive() { when(mCoreMock.getAI()).thenReturn( null ); assertThat(mSUT.isAlive()).isFalse(); mSUT.stopManagement(); assertThat(mSUT.isAlive()).isFalse(); verify(mLoggerMock, never()).info("RestartAiServerManagement stopped."); } |
### Question:
ReloadAiManagement extends Thread { @Override public void run(){ while( mAiActive ){ try { if(Core.getInstance().getAI() != null && Core.getInstance().getAI().wantRestart()){ Core.getInstance().initializeAI(); Core.getInstance().resumeAI(); Thread.sleep( 500 ); } Thread.sleep( 50 ); } catch ( Exception vException ) { Core.getLogger().error( "Error while waiting in RestartAiServerManagement.", vException ); } } } ReloadAiManagement(); static ReloadAiManagement getInstance(); void close(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); }### Answer:
@Test public void testRunWithoutStart() throws Exception { when(mCoreMock.getAI()).thenReturn( mArtificialIntelligenceMock ); assertThat(mSUT.isAlive()).isFalse(); mSUT.run(); assertThat(mSUT.isAlive()).isFalse(); verifyZeroInteractions(mArtificialIntelligenceMock); } |
### Question:
ToServerManagement extends Thread { @Override public void start(){ this.startManagement(); } ToServerManagement(); static ToServerManagement getInstance(); void close(); void resumeManagement(); boolean isSuspended(); void suspendManagement(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isSendingMessages(); }### Answer:
@Test public void testStartWithoutNetworkConnection() { when(mCoreMock.getServerConnection()).thenReturn( null ); try{ mSUT.start(); fail("Expected Nullpointerexception"); } catch( Exception vExpectedException ) { assertThat(vExpectedException).isInstanceOf(NullPointerException.class); assertThat(vExpectedException.getMessage()).isEqualToIgnoringCase( "NetworkCommunication cannot be NULL when starting ToServerManagement." ); } }
@Test public void testStartWithNetworkConnectionAndNotAlive() { when(mCoreMock.getServerConnection()).thenReturn( mNetworkCommunicationMock ); when(mCoreMock.getAI()).thenReturn( null ); mSUT.start(); assertThat(mSUT.isAlive()).isTrue(); verify(mLoggerMock).info("ToServerManagement started."); } |
### Question:
ProfileInfoResource { @GetMapping("/profile-info") public ProfileInfoVM getActiveProfiles() { String[] activeProfiles = DefaultProfileUtil.getActiveProfiles(env); return new ProfileInfoVM(activeProfiles, getRibbonEnv(activeProfiles)); } ProfileInfoResource(Environment env, JHipsterProperties jHipsterProperties); @GetMapping("/profile-info") ProfileInfoVM getActiveProfiles(); }### Answer:
@Test public void getActiveProfilesTest() throws Exception { MvcResult res = mock.perform(get("/api/profile-info") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andReturn(); assertTrue(res.getResponse().getContentAsString().contains("\"activeProfiles\":[\""+profiles[0]+"\"]")); } |
### Question:
TokenProvider { public boolean validateToken(String authToken) { try { Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken); return true; } catch (SignatureException e) { log.info("Invalid JWT signature."); log.trace("Invalid JWT signature trace: {}", e); } catch (MalformedJwtException e) { log.info("Invalid JWT token."); log.trace("Invalid JWT token trace: {}", e); } catch (ExpiredJwtException e) { log.info("Expired JWT token."); log.trace("Expired JWT token trace: {}", e); } catch (UnsupportedJwtException e) { log.info("Unsupported JWT token."); log.trace("Unsupported JWT token trace: {}", e); } catch (IllegalArgumentException e) { log.info("JWT token compact of handler are invalid."); log.trace("JWT token compact of handler are invalid trace: {}", e); } return false; } TokenProvider(JHipsterProperties jHipsterProperties); @PostConstruct void init(); String createToken(Authentication authentication, Boolean rememberMe); Authentication getAuthentication(String token); boolean validateToken(String authToken); }### Answer:
@Test public void testReturnFalseWhenJWTisUnsupported() { String unsupportedToken = createUnsupportedToken(); boolean isTokenValid = tokenProvider.validateToken(unsupportedToken); assertThat(isTokenValid).isEqualTo(false); } |
### Question:
LogsResource { @GetMapping("/logs") @Timed public List<LoggerVM> getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); return context.getLoggerList() .stream() .map(LoggerVM::new) .collect(Collectors.toList()); } @GetMapping("/logs") @Timed List<LoggerVM> getList(); @PutMapping("/logs") @ResponseStatus(HttpStatus.NO_CONTENT) @Timed void changeLevel(@RequestBody LoggerVM jsonLogger); }### Answer:
@Test public void getListTest() throws Exception { mock.perform(get("/management/logs") .accept(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); } |
### Question:
LogsResource { @PutMapping("/logs") @ResponseStatus(HttpStatus.NO_CONTENT) @Timed public void changeLevel(@RequestBody LoggerVM jsonLogger) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel())); } @GetMapping("/logs") @Timed List<LoggerVM> getList(); @PutMapping("/logs") @ResponseStatus(HttpStatus.NO_CONTENT) @Timed void changeLevel(@RequestBody LoggerVM jsonLogger); }### Answer:
@Test public void changeLevelTest() throws Exception { LoggerVM logger = new LoggerVM(); logger.setLevel("ERROR"); logger.setName("ROOT"); mock.perform(put("/management/logs") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(new ObjectMapper().writeValueAsString(logger))) .andExpect(status().isNoContent()); MvcResult res = mock.perform(get("/management/logs") .accept(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andReturn(); assertTrue(res.getResponse().getContentAsString().contains("\"name\":\""+logger.getName() +"\",\"level\":\""+logger.getLevel()+"\"")); } |
### Question:
SshResource { @GetMapping(value = "/ssh/public_key", produces = MediaType.TEXT_PLAIN_VALUE) @Timed public ResponseEntity<String> eureka() { try { String publicKey = getPublicKey(); if(publicKey != null) return new ResponseEntity<>(publicKey, HttpStatus.OK); } catch (IOException e) { log.warn("SSH public key could not be loaded: {}", e.getMessage()); } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } @GetMapping(value = "/ssh/public_key", produces = MediaType.TEXT_PLAIN_VALUE) @Timed ResponseEntity<String> eureka(); }### Answer:
@Test public void eurekaTest() throws Exception { Mockito.doReturn(null).when(ssh).getPublicKey(); mock.perform(get("/api/ssh/public_key")) .andExpect(status().isNotFound()); Mockito.doReturn("key").when(ssh).getPublicKey(); mock.perform(get("/api/ssh/public_key")) .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN)) .andExpect(content().string("key")) .andExpect(status().isOk()); } |
### Question:
ExceptionTranslator { @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ParameterizedErrorVM processParameterizedValidationError(CustomParameterizedException ex) { return ex.getErrorVM(); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ErrorVM processValidationError(MethodArgumentNotValidException ex); @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ParameterizedErrorVM processParameterizedValidationError(CustomParameterizedException ex); @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody ErrorVM processAccessDeniedException(AccessDeniedException e); @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception); @ExceptionHandler(Exception.class) ResponseEntity<ErrorVM> processRuntimeException(Exception ex); }### Answer:
@Test public void processParameterizedValidationErrorTest() throws Exception { SecurityContext securityContext = Mockito.mock(SecurityContext.class); Mockito.when(securityContext.getAuthentication()).thenThrow(new CustomParameterizedException(null)); SecurityContextHolder.setContext(securityContext); MvcResult res = mock.perform(get("/api/account")) .andExpect(status().isBadRequest()) .andReturn(); assertThat(res.getResolvedException(), instanceOf(CustomParameterizedException.class)); } |
### Question:
ExceptionTranslator { @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody public ErrorVM processAccessDeniedException(AccessDeniedException e) { return new ErrorVM(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ErrorVM processValidationError(MethodArgumentNotValidException ex); @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ParameterizedErrorVM processParameterizedValidationError(CustomParameterizedException ex); @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody ErrorVM processAccessDeniedException(AccessDeniedException e); @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception); @ExceptionHandler(Exception.class) ResponseEntity<ErrorVM> processRuntimeException(Exception ex); }### Answer:
@Test public void processAccessDeniedExceptionTest() throws Exception { SecurityContext securityContext = Mockito.mock(SecurityContext.class); Mockito.when(securityContext.getAuthentication()).thenThrow(new AccessDeniedException(null)); SecurityContextHolder.setContext(securityContext); MvcResult res = mock.perform(get("/api/account")) .andExpect(status().isForbidden()) .andReturn(); assertThat(res.getResolvedException(), instanceOf(AccessDeniedException.class)); } |
### Question:
ExceptionTranslator { @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) public ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) { return new ErrorVM(ErrorConstants.ERR_METHOD_NOT_SUPPORTED, exception.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ErrorVM processValidationError(MethodArgumentNotValidException ex); @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ParameterizedErrorVM processParameterizedValidationError(CustomParameterizedException ex); @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody ErrorVM processAccessDeniedException(AccessDeniedException e); @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception); @ExceptionHandler(Exception.class) ResponseEntity<ErrorVM> processRuntimeException(Exception ex); }### Answer:
@Test public void processMethodNotSupportedExceptionTest() throws Exception { MvcResult res = mock.perform(post("/api/account") .content("{\"testFakeParam\"}")) .andExpect(status().isMethodNotAllowed()) .andReturn(); assertThat(res.getResolvedException(), instanceOf(HttpRequestMethodNotSupportedException.class)); } |
### Question:
ExceptionTranslator { @ExceptionHandler(Exception.class) public ResponseEntity<ErrorVM> processRuntimeException(Exception ex) { BodyBuilder builder; ErrorVM errorVM; ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class); if (responseStatus != null) { builder = ResponseEntity.status(responseStatus.value()); errorVM = new ErrorVM("error." + responseStatus.value().value(), responseStatus.reason()); } else { builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR); errorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, "Internal server error"); } return builder.body(errorVM); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ErrorVM processValidationError(MethodArgumentNotValidException ex); @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ParameterizedErrorVM processParameterizedValidationError(CustomParameterizedException ex); @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody ErrorVM processAccessDeniedException(AccessDeniedException e); @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception); @ExceptionHandler(Exception.class) ResponseEntity<ErrorVM> processRuntimeException(Exception ex); }### Answer:
@Test public void processRuntimeExceptionTest() throws Exception { SecurityContext securityContext = Mockito.mock(SecurityContext.class); Mockito.when(securityContext.getAuthentication()).thenThrow(new RuntimeException()); SecurityContextHolder.setContext(securityContext); MvcResult res = mock.perform(get("/api/account")) .andExpect(status().isInternalServerError()) .andReturn(); assertThat(res.getResolvedException(), instanceOf(RuntimeException.class)); } |
### Question:
CustomParameterizedException extends RuntimeException { public ParameterizedErrorVM getErrorVM() { return new ParameterizedErrorVM(message, paramMap); } CustomParameterizedException(String message, String... params); CustomParameterizedException(String message, Map<String, String> paramMap); ParameterizedErrorVM getErrorVM(); }### Answer:
@Test public void getErrorVMTest() throws Exception { CustomParameterizedException exc = new CustomParameterizedException("Test"); try { throw exc; } catch ( Exception exception ) { assertTrue(exception instanceof CustomParameterizedException); CustomParameterizedException exceptionCast = (CustomParameterizedException) exception; assertNotNull(exceptionCast.getErrorVM()); assertNotNull(exceptionCast.getErrorVM().getMessage()); assertEquals("Test", exceptionCast.getErrorVM().getMessage()); } exc = new CustomParameterizedException(null); try { throw exc; } catch ( Exception exception ) { assertTrue(exception instanceof CustomParameterizedException); CustomParameterizedException exceptionCast = (CustomParameterizedException) exception; assertNotNull(exceptionCast.getErrorVM()); assertNull(exceptionCast.getErrorVM().getMessage()); } } |
### Question:
FieldErrorVM implements Serializable { public String getObjectName() { return objectName; } FieldErrorVM(String dto, String field, String message); String getObjectName(); String getField(); String getMessage(); }### Answer:
@Test public void getObjectNameTest() throws Exception { FieldErrorVM vm = new FieldErrorVM(null, null, null); assertNull(vm.getObjectName()); vm = new FieldErrorVM("dto", "field", "message"); assertEquals("dto", vm.getObjectName()); } |
### Question:
FieldErrorVM implements Serializable { public String getField() { return field; } FieldErrorVM(String dto, String field, String message); String getObjectName(); String getField(); String getMessage(); }### Answer:
@Test public void getFieldTest() throws Exception { FieldErrorVM vm = new FieldErrorVM(null, null, null); assertNull(vm.getField()); vm = new FieldErrorVM("dto", "field", "message"); assertEquals("field", vm.getField()); } |
### Question:
FieldErrorVM implements Serializable { public String getMessage() { return message; } FieldErrorVM(String dto, String field, String message); String getObjectName(); String getField(); String getMessage(); }### Answer:
@Test public void getMessageTest() throws Exception { FieldErrorVM vm = new FieldErrorVM(null, null, null); assertNull(vm.getMessage()); vm = new FieldErrorVM("dto", "field", "message"); assertEquals("message", vm.getMessage()); } |
### Question:
ErrorVM implements Serializable { public void add(String objectName, String field, String message) { if (fieldErrors == null) { fieldErrors = new ArrayList<>(); } fieldErrors.add(new FieldErrorVM(objectName, field, message)); } ErrorVM(String message); ErrorVM(String message, String description); ErrorVM(String message, String description, List<FieldErrorVM> fieldErrors); void add(String objectName, String field, String message); String getMessage(); String getDescription(); List<FieldErrorVM> getFieldErrors(); }### Answer:
@Test public void addTest() throws Exception { assertNull(vm1.getFieldErrors()); assertNull(vm2.getFieldErrors()); assertNotNull(vm3.getFieldErrors()); assertNull(vm1null.getFieldErrors()); assertNull(vm2null.getFieldErrors()); assertNull(vm3null.getFieldErrors()); vm1.add("testObjectName", "testField", "testMsg"); vm2.add("testObjectName", "testField", "testMsg"); vm3.add("testObjectName", "testField", "testMsg"); vm1null.add("testObjectName", "testField", "testMsg"); vm2null.add("testObjectName", "testField", "testMsg"); vm3null.add("testObjectName", "testField", "testMsg"); assertNotNull(vm1.getFieldErrors()); assertFalse(vm1.getFieldErrors().isEmpty()); assertNotNull(vm2.getFieldErrors()); assertFalse(vm2.getFieldErrors().isEmpty()); assertNotNull(vm3.getFieldErrors()); assertFalse(vm3.getFieldErrors().isEmpty()); assertNotNull(vm1null.getFieldErrors()); assertFalse(vm1null.getFieldErrors().isEmpty()); assertNotNull(vm2null.getFieldErrors()); assertFalse(vm2null.getFieldErrors().isEmpty()); assertNotNull(vm3null.getFieldErrors()); assertFalse(vm3null.getFieldErrors().isEmpty()); } |
### Question:
ErrorVM implements Serializable { public String getMessage() { return message; } ErrorVM(String message); ErrorVM(String message, String description); ErrorVM(String message, String description, List<FieldErrorVM> fieldErrors); void add(String objectName, String field, String message); String getMessage(); String getDescription(); List<FieldErrorVM> getFieldErrors(); }### Answer:
@Test public void getMessageTest() throws Exception { assertEquals(message, vm1.getMessage()); assertEquals(message, vm2.getMessage()); assertEquals(message, vm3.getMessage()); assertNull(vm1null.getMessage()); assertNull(vm2null.getMessage()); assertNull(vm3null.getMessage()); } |
### Question:
ErrorVM implements Serializable { public String getDescription() { return description; } ErrorVM(String message); ErrorVM(String message, String description); ErrorVM(String message, String description, List<FieldErrorVM> fieldErrors); void add(String objectName, String field, String message); String getMessage(); String getDescription(); List<FieldErrorVM> getFieldErrors(); }### Answer:
@Test public void getDescriptionTest() throws Exception { assertNull(vm1.getDescription()); assertEquals(description, vm2.getDescription()); assertEquals(description, vm3.getDescription()); assertNull(vm1null.getDescription()); assertNull(vm2null.getDescription()); assertNull(vm3null.getDescription()); } |
### Question:
ParameterizedErrorVM implements Serializable { public String getMessage() { return message; } ParameterizedErrorVM(String message, Map<String, String> paramMap); String getMessage(); Map<String, String> getParams(); }### Answer:
@Test public void getMessageTest() { ParameterizedErrorVM vm = new ParameterizedErrorVM(null, null); assertNull(vm.getMessage()); Map<String, String> paramMap = new HashMap<>(); paramMap.put("param1", "param1"); paramMap.put("param2", "param2"); vm = new ParameterizedErrorVM("message", paramMap); assertEquals("message", vm.getMessage()); } |
### Question:
ParameterizedErrorVM implements Serializable { public Map<String, String> getParams() { return paramMap; } ParameterizedErrorVM(String message, Map<String, String> paramMap); String getMessage(); Map<String, String> getParams(); }### Answer:
@Test public void getParamsTest() { ParameterizedErrorVM vm = new ParameterizedErrorVM(null, null); assertNull(vm.getMessage()); Map<String, String> paramMap = new HashMap<>(); paramMap.put("param1", "param1"); paramMap.put("param2", "param2"); vm = new ParameterizedErrorVM("message", paramMap); assertTrue(vm.getParams().size() == 2); } |
### Question:
EurekaVM { public List<Map<String, Object>> getApplications() { return applications; } List<Map<String, Object>> getApplications(); void setApplications(List<Map<String, Object>> applications); Map<String, Object> getStatus(); void setStatus(Map<String, Object> status); }### Answer:
@Test public void getApplicationsTest() throws Exception { List<Map<String, Object>> list = eureka.getApplications(); assertNull(list); eureka.setApplications(initFakeApplicationsList()); list = eureka.getApplications(); assertNotNull(list); assertTrue(list.size()==2); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.