method2testcases
stringlengths
118
3.08k
### Question: DirectoryWithAutomaticCreation implements Directory { @Override public final void remove() throws IOException { this.directory.remove(); } DirectoryWithAutomaticCreation(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }### Answer: @Test public void remove() throws IOException { final FileSystemPathBase path = new FileSystemPathBase(testFolder.newFolder().toString()); new DirectoryWithAutomaticCreation(new DirectoryBase(path)).remove(); MatcherAssert.assertThat("The directory wasn't removed", !path.exist()); }
### Question: DirectoryWithAutomaticCreation implements Directory { @Override public final boolean exist() { try { this.create(); return true; } catch (IOException e) { throw new RuntimeException(e); } } DirectoryWithAutomaticCreation(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }### Answer: @Test public void exist() throws IOException { final FileSystemPathBase path = new FileSystemPathBase(testFolder.newFolder().toString(), "a"); new DirectoryWithAutomaticCreation(new DirectoryBase(path)).exist(); MatcherAssert.assertThat("The directory wasn't created", path.exist()); }
### Question: DirectoryWithAutomaticCreation implements Directory { @Override public final Path path() { try { this.create(); return this.directory.path(); } catch (IOException e) { throw new RuntimeException(e); } } DirectoryWithAutomaticCreation(Directory directory); @Override final void create(); @Override final void remove(); @Override final Path path(); @Override final boolean exist(); }### Answer: @Test public void path() throws IOException { final FileSystemPathBase path = new FileSystemPathBase(testFolder.newFolder().toString(), "a"); new DirectoryWithAutomaticCreation(new DirectoryBase(path)).path(); MatcherAssert.assertThat("The directory wasn't created", path.exist()); }
### Question: SuiteFromClasses implements SunshineSuite { @Override public final List<SunshineTest> tests() throws SuiteException { return Arrays.stream(this.classes).map(TestFromClass::new).collect(Collectors.toList()); } SuiteFromClasses(Class... clazz); @Override final List<SunshineTest> tests(); }### Answer: @Test public void tests() throws SuiteException { MatcherAssert.assertThat( new SuiteFromClasses(SuiteFromClasses.class).tests(), Matchers.hasSize(1)); }
### Question: FileSystemOfClasses implements FileSystem { @Override public List<FileSystemPath> files() throws FileSystemException { return fileSystem.files(); } FileSystemOfClasses(FileSystem fileSystem); @Override List<FileSystemPath> files(); }### Answer: @Test public void onlyFilesInFileSystem() throws FileSystemException { MatcherAssert.assertThat( new FileSystemOfClasses( new FileSystem.Fake( Arrays.asList( new FileSystemPath.Fake("SomeTest.class"), new FileSystemPath.Fake("some-file.txt")))) .files(), Matchers.hasSize(1)); } @Test public void filesAndJarsInFileSystem() throws FileSystemException { MatcherAssert.assertThat( new FileSystemOfClasses(new FileSystemOfJarFile("build/sample-tests.jar")).files(), Matchers.hasSize(5)); }
### Question: Junit4Kernel implements Kernel<RunListener> { @Override public final Status status() throws KernelException { try { return new JunitStatus(this.junit.run(new Computer(), this.suiteForRun.tests())); } catch (SuiteException e) { throw new KernelException("Some problem occurs in the JUnit 4 kernel", e); } } Junit4Kernel(Suite<Class<?>[]> suite); private Junit4Kernel(JUnitCore jUnitCore, Suite<Class<?>[]> suite); @Override final Status status(); @Override final Junit4Kernel with(RunListener... listeners); }### Answer: @Test public void run() throws KernelException { MatcherAssert.assertThat( new Junit4Kernel(() -> new Class[] {}).status().code(), Matchers.equalTo((short) 0)); } @Test(expected = KernelException.class) public void runWithFail() throws KernelException { new Junit4Kernel( () -> { throw new SuiteException("Fail"); }) .status(); }
### Question: Junit4Kernel implements Kernel<RunListener> { @Override public final Junit4Kernel with(RunListener... listeners) { final JUnitCore jUnitCore = new JUnitCore(); Arrays.stream(listeners).forEach(jUnitCore::addListener); return new Junit4Kernel(jUnitCore, this.suiteForRun); } Junit4Kernel(Suite<Class<?>[]> suite); private Junit4Kernel(JUnitCore jUnitCore, Suite<Class<?>[]> suite); @Override final Status status(); @Override final Junit4Kernel with(RunListener... listeners); }### Answer: @Test public void with() throws KernelException { final Listener l1 = new Listener(); final Listener l2 = new Listener(); new Junit4Kernel(() -> new Class[] {}).with(l1).with(l2).status(); MatcherAssert.assertThat(l1, Matchers.not(Matchers.equalTo(l2))); }
### Question: JunitSuite implements Suite<Class<?>[]> { @Override public final Class<?>[] tests() throws SuiteException { List<Class<?>> tests = new ArrayList<>(); for (SunshineTest test : this.suite.tests()) { try { tests.add(test.object()); } catch (TestException e) { throw new SuiteException(e); } } return tests.toArray(new Class[] {}); } JunitSuite(Condition filter); JunitSuite(FileSystem fileSystem, Condition filter); JunitSuite(SunshineSuite classesAsSuite); @Override final Class<?>[] tests(); }### Answer: @Test public void testDefaultSuite() throws SuiteException { MatcherAssert.assertThat( new JunitSuite(() -> Collections.emptyList()).tests(), Matchers.arrayWithSize(0)); } @Test public void testDefaultFileSystemAndTestsFilter() throws SuiteException { MatcherAssert.assertThat( new JunitSuite(new FileSystem.Fake(), new Condition.Fake(false)).tests(), Matchers.arrayWithSize(0)); } @Test public void testDefaultTestsFilter() throws SuiteException { MatcherAssert.assertThat( new JunitSuite(new Condition.Fake(false)).tests(), Matchers.arrayWithSize(0)); }
### Question: JunitStatus implements Status { @Override public final short code() { if (this.status.wasSuccessful()) { return (short) 0; } return (short) 1; } JunitStatus(Result result); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }### Answer: @Test public void codeIfPassed() { MatcherAssert.assertThat( new JunitStatus(new FakeResult(true, 0, 0, 0)).code(), Matchers.is((short) 0)); } @Test public void codeIfFailed() { MatcherAssert.assertThat( new JunitStatus(new FakeResult(false, 0, 0, 0)).code(), Matchers.is((short) 1)); }
### Question: JunitStatus implements Status { @Override public final int runCount() { return status.getRunCount(); } JunitStatus(Result result); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }### Answer: @Test public void runCount() { MatcherAssert.assertThat( new JunitStatus(new FakeResult(false, 3, 0, 0)).runCount(), Matchers.is(3)); }
### Question: JunitStatus implements Status { @Override public final int failureCount() { return status.getFailureCount(); } JunitStatus(Result result); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }### Answer: @Test public void failureCount() { MatcherAssert.assertThat( new JunitStatus(new FakeResult(false, 0, 2, 0)).failureCount(), Matchers.is(2)); }
### Question: JunitStatus implements Status { @Override public final int ignoreCount() { return status.getIgnoreCount(); } JunitStatus(Result result); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }### Answer: @Test public void ignoreCount() { MatcherAssert.assertThat( new JunitStatus(new FakeResult(false, 0, 0, 5)).ignoreCount(), Matchers.is(5)); }
### Question: Junit5Status implements Status { @Override public final short code() { return this.summary.getTotalFailureCount() == 0 ? this.passed : this.failed; } Junit5Status(TestExecutionSummary testExecutionSummary); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }### Answer: @Test void codePassed() { MatcherAssert.assertThat( new Junit5Status(new Summary(1, 0, 0, 0)).code(), Matchers.is((short) 0)); } @Test void codeFailed() { MatcherAssert.assertThat( new Junit5Status(new Summary(1, 0, 0, 1)).code(), Matchers.is((short) 1)); }
### Question: Junit5Status implements Status { @Override public final int runCount() { return Math.toIntExact(this.summary.getTestsFoundCount()); } Junit5Status(TestExecutionSummary testExecutionSummary); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }### Answer: @Test void runCount() { MatcherAssert.assertThat( new Junit5Status(new Summary(5, 4, 3, 1)).runCount(), Matchers.is(5)); }
### Question: Junit5Status implements Status { @Override public final int failureCount() { return Math.toIntExact(this.summary.getTestsFailedCount()); } Junit5Status(TestExecutionSummary testExecutionSummary); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }### Answer: @Test void failureCount() { MatcherAssert.assertThat( new Junit5Status(new Summary(5, 4, 3, 1)).failureCount(), Matchers.is(4)); }
### Question: Junit5Status implements Status { @Override public final int ignoreCount() { return Math.toIntExact(this.summary.getTestsSkippedCount()); } Junit5Status(TestExecutionSummary testExecutionSummary); @Override final short code(); @Override final int runCount(); @Override final int failureCount(); @Override final int ignoreCount(); }### Answer: @Test void ignoreCount() { MatcherAssert.assertThat( new Junit5Status(new Summary(5, 4, 3, 1)).ignoreCount(), Matchers.is(3)); }
### Question: Junit5Kernel implements Kernel<TestExecutionListener> { @Override public final Status status() throws KernelException { try { launcher.execute( LauncherDiscoveryRequestBuilder.request() .selectors( tests.tests().stream() .map( sunshineTest -> DiscoverySelectors.selectClass( sunshineTest.toString())) .toArray(DiscoverySelector[]::new)) .build()); return new Junit5Status(this.reporter.getSummary()); } catch (SuiteException e) { throw new KernelException("Some problem occurs in the Junit5Kernel", e); } } Junit5Kernel(SunshineSuite sunshineSuite); private Junit5Kernel(Launcher launcher, SunshineSuite sunshineSuite); @Override final Status status(); @Override final Kernel<TestExecutionListener> with( TestExecutionListener... testExecutionListeners); }### Answer: @Test public void run() throws KernelException { MatcherAssert.assertThat( new Junit5Kernel(ArrayList::new).status().code(), Matchers.equalTo((short) 0)); }
### Question: Junit5Kernel implements Kernel<TestExecutionListener> { @Override public final Kernel<TestExecutionListener> with( TestExecutionListener... testExecutionListeners) { final Launcher fork = LauncherFactory.create(); fork.registerTestExecutionListeners(testExecutionListeners); return new Junit5Kernel(fork, this.tests); } Junit5Kernel(SunshineSuite sunshineSuite); private Junit5Kernel(Launcher launcher, SunshineSuite sunshineSuite); @Override final Status status(); @Override final Kernel<TestExecutionListener> with( TestExecutionListener... testExecutionListeners); }### Answer: @Test public void with() throws KernelException { final Listener l1 = new Listener(); final Listener l2 = new Listener(); new Junit5Kernel(ArrayList::new).with(l1).with(l2).status(); MatcherAssert.assertThat(l1, Matchers.not(Matchers.equalTo(l2))); }
### Question: FileSystemOfJarFile implements FileSystem { @Override public List<FileSystemPath> files() throws FileSystemException { try { List<FileSystemPath> data = new ArrayList<>(); ZipInputStream zip = new ZipInputStream(new FileInputStream(jarPath)); for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { data.add(new FileSystemPathBase(entry.getName())); } return data; } catch (IOException e) { throw new FileSystemException(e); } } FileSystemOfJarFile(FileSystemPath jarPath); FileSystemOfJarFile(String jarPath); @Override List<FileSystemPath> files(); }### Answer: @Test public void files() throws FileSystemException { MatcherAssert.assertThat( new FileSystemOfJarFile("build/sample-tests.jar").files(), Matchers.hasItem(new FileSystemPathBase("org/tatools/testng/Test1.class"))); } @Test(expected = FileSystemException.class) public void incorrectPath() throws FileSystemException { new FileSystemOfJarFile("faffasfas").files(); }
### Question: SuiteFromFileSystem implements SunshineSuite { @Override public final List<SunshineTest> tests() throws SuiteException { try { return fileSystem.files().stream() .map(f -> new TestFromFile(f.path().toString())) .collect(Collectors.toList()); } catch (FileSystemException e) { throw new SuiteException(e); } } SuiteFromFileSystem(FileSystem fileSystem); @Override final List<SunshineTest> tests(); }### Answer: @Test public void tests() throws SuiteException { MatcherAssert.assertThat( new SuiteFromFileSystem(new FileSystem.Fake(new FileSystemPath.Fake("a"))).tests(), Matchers.hasSize(1)); }
### Question: FileBase implements File { @Override public final void write(String data) throws IOException { Files.write(this.path(), data.getBytes()); } FileBase(Directory directory, String file); FileBase(String directory, String file); FileBase(Path directory, String file); FileBase(FileSystemPath fileSystemPath); @Override final Path path(); @Override final boolean exist(); @Override final void write(String data); }### Answer: @Test public void write() throws IOException { final FileBase file = new FileBase(testFolder.getRoot().getAbsolutePath(), "ccc"); file.write("dasd"); MatcherAssert.assertThat(Files.exists(file.path()), Matchers.is(true)); }
### Question: FileSystemOfJarFiles implements FileSystem { @Override public List<FileSystemPath> files() throws FileSystemException { return new FileSystemOfFileSystems(mapping.objects(fileSystem)).files(); } FileSystemOfJarFiles(FileSystem fileSystem); private FileSystemOfJarFiles(FileSystem fileSystem, Mapping mapping); @Override List<FileSystemPath> files(); }### Answer: @Test public void files() throws FileSystemException { MatcherAssert.assertThat( new FileSystemOfJarFiles( new FileSystem.Fake( new FileSystemPath.Fake("build/sample-tests.jar"), new FileSystemPath.Fake("build/sample-tests.jar"))) .files(), Matchers.hasSize(20)); }
### Question: ObjectClassNameBuilder { public String build() { final StringBuilder nameBuilder = new StringBuilder(); Collections.reverse(enclosingClassSimpleNames); for (String enclosingClassSimpleName : enclosingClassSimpleNames) { nameBuilder.append(enclosingClassSimpleName).append("$"); } return nameBuilder + targetClassSimpleName + RETAINER_CLASS_SUFFIX; } ObjectClassNameBuilder(String targetClassSimpleName); ObjectClassNameBuilder addEnclosingClassSimpleName(String enclosingClassSimpleName); String build(); }### Answer: @Test public void testBuild() { final String objectClassName = new ObjectClassNameBuilder("TargetClass").build(); assertEquals("TargetClass_Retainer", objectClassName); }
### Question: Lyra { @NonNull public static Lyra instance() { if (!isInitialized()) { throw new NullPointerException("Instance not initialized. You have to build it in your application."); } return instance; } @SuppressLint("NewApi") private Lyra(@NonNull Application application, @NonNull CoderRetriever coderRetriever, @NonNull FieldsRetriever fieldsRetriever, boolean autoSaveActivities); static Builder with(@NonNull Application application); @SuppressLint("NewApi") static void destroy(); static boolean isInitialized(); @NonNull static Lyra instance(); @NonNull static String getKeyFromField(@NonNull Field field); void saveState(@NonNull Object stateHolder, @NonNull Bundle state); void restoreState(@NonNull Object stateHolder, @Nullable Bundle state); Parcelable saveState(@NonNull View stateHolder, @Nullable Parcelable state); Parcelable restoreState(@NonNull View stateHolder, @Nullable Parcelable state); static final String SUB_BUNDLE_KEY; static final String VIEW_SUPER_STATE_BUNDLE_KEY; }### Answer: @Test public void testInstanceNotNull() { assertNotNull(Lyra.instance()); }
### Question: ShortCoder extends BaseCoder<Short> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Short fieldValue) { state.putShort(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Short fieldValue); }### Answer: @Test public void testSerializeShortPrimitive() { short expectedValue = 9; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getShort(randomKey())); } @Test public void testSerializeShortObject() { Short expectedValue = 9; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, (Short) bundle().getShort(randomKey())); }
### Question: CharArrayCoder extends BaseCoder<char[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull char[] fieldValue) { state.putCharArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull char[] fieldValue); }### Answer: @Test public void testSerializeCharArray() { char[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getCharArray(randomKey())); }
### Question: Lyra { @SuppressLint("NewApi") public static void destroy() { if (isInitialized()) { if (instance.mAutomaticSaveStateManager != null) { instance.mApplication.unregisterActivityLifecycleCallbacks(instance.mAutomaticSaveStateManager); } instance.mApplication = null; instance = null; } } @SuppressLint("NewApi") private Lyra(@NonNull Application application, @NonNull CoderRetriever coderRetriever, @NonNull FieldsRetriever fieldsRetriever, boolean autoSaveActivities); static Builder with(@NonNull Application application); @SuppressLint("NewApi") static void destroy(); static boolean isInitialized(); @NonNull static Lyra instance(); @NonNull static String getKeyFromField(@NonNull Field field); void saveState(@NonNull Object stateHolder, @NonNull Bundle state); void restoreState(@NonNull Object stateHolder, @Nullable Bundle state); Parcelable saveState(@NonNull View stateHolder, @Nullable Parcelable state); Parcelable restoreState(@NonNull View stateHolder, @Nullable Parcelable state); static final String SUB_BUNDLE_KEY; static final String VIEW_SUPER_STATE_BUNDLE_KEY; }### Answer: @Test public void testDestroy() { Lyra.destroy(); assertFalse(Lyra.isInitialized()); }
### Question: StringCoder extends BaseCoder<String> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull String fieldValue) { state.putString(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull String fieldValue); }### Answer: @Test public void testSerializeString() { String expectedValue = "test"; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getString(randomKey())); }
### Question: SizeFCoder extends BaseCoder<SizeF> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull SizeF fieldValue) { state.putSizeF(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull SizeF fieldValue); }### Answer: @Test public void testSerializeSizeF() { SizeF expectedValue = new SizeF(9, 5); mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getSizeF(randomKey())); }
### Question: SizeCoder extends BaseCoder<Size> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Size fieldValue) { state.putSize(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Size fieldValue); }### Answer: @SuppressWarnings("NewApi") @Test public void testSerializeSize() { Size expectedValue = new Size(9, 5); mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getSize(randomKey())); }
### Question: StringArrayCoder extends BaseCoder<String[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull String[] fieldValue) { state.putStringArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull String[] fieldValue); }### Answer: @Test public void testSerializeStringArray() { String[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getStringArray(randomKey())); }
### Question: CharCoder extends BaseCoder<Character> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Character fieldValue) { state.putChar(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Character fieldValue); }### Answer: @Test public void testSerializeCharPrimitive() { char expectedValue = 'x'; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getChar(randomKey())); } @Test public void testSerializeCharObject() { Character expectedValue = 'x'; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, ((Character) bundle().getChar(randomKey()))); }
### Question: FloatArrayCoder extends BaseCoder<float[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull float[] fieldValue) { state.putFloatArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull float[] fieldValue); }### Answer: @Test public void testSerializeFloatArray() { float[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getFloatArray(randomKey())); }
### Question: BooleanArrayCoder extends BaseCoder<boolean[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull boolean[] fieldValue) { state.putBooleanArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull boolean[] fieldValue); }### Answer: @Test public void testSerializeBooleanArray() { boolean[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getBooleanArray(randomKey())); }
### Question: ByteCoder extends BaseCoder<Byte> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Byte fieldValue) { state.putByte(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Byte fieldValue); }### Answer: @Test public void testSerializeBytePrimitive() { byte expectedValue = 2; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getByte(randomKey())); } @Test public void testSerializeByteObject() { Byte expectedValue = 2; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, ((Byte) bundle().getByte(randomKey()))); }
### Question: Lyra { public static boolean isInitialized() { return instance != null; } @SuppressLint("NewApi") private Lyra(@NonNull Application application, @NonNull CoderRetriever coderRetriever, @NonNull FieldsRetriever fieldsRetriever, boolean autoSaveActivities); static Builder with(@NonNull Application application); @SuppressLint("NewApi") static void destroy(); static boolean isInitialized(); @NonNull static Lyra instance(); @NonNull static String getKeyFromField(@NonNull Field field); void saveState(@NonNull Object stateHolder, @NonNull Bundle state); void restoreState(@NonNull Object stateHolder, @Nullable Bundle state); Parcelable saveState(@NonNull View stateHolder, @Nullable Parcelable state); Parcelable restoreState(@NonNull View stateHolder, @Nullable Parcelable state); static final String SUB_BUNDLE_KEY; static final String VIEW_SUPER_STATE_BUNDLE_KEY; }### Answer: @Test public void testIsInitialized() { assertTrue(Lyra.isInitialized()); }
### Question: LongArrayCoder extends BaseCoder<long[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull long[] fieldValue) { state.putLongArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull long[] fieldValue); }### Answer: @Test public void testSerializeLongArray() { long[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getLongArray(randomKey())); }
### Question: ByteArrayCoder extends BaseCoder<byte[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull byte[] fieldValue) { state.putByteArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull byte[] fieldValue); }### Answer: @Test public void testSerializeByteArray() { byte[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getByteArray(randomKey())); }
### Question: DoubleCoder extends BaseCoder<Double> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Double fieldValue) { state.putDouble(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Double fieldValue); }### Answer: @Test public void testSerializeDoublePrimitive() { double expectedValue = 9.0; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getDouble(randomKey()), 0); } @Test public void testSerializeDoubleObject() { Double expectedValue = 9.0; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getDouble(randomKey())); }
### Question: IBinderCoder extends BaseCoder<IBinder> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull IBinder fieldValue) { BundleCompat.putBinder(state, key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull IBinder fieldValue); }### Answer: @Test public void testSerializeIBinder() { IBinder expectedValue = new Binder(); mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, BundleCompat.getBinder(bundle(), randomKey())); }
### Question: IntCoder extends BaseCoder<Integer> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Integer fieldValue) { state.putInt(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Integer fieldValue); }### Answer: @Test public void testSerializeIntPrimitive() { int expectedValue = 9; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getInt(randomKey())); } @Test public void testSerializeIntObject() { Integer expectedValue = 9; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, (Integer) bundle().getInt(randomKey())); }
### Question: DoubleArrayCoder extends BaseCoder<double[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull double[] fieldValue) { state.putDoubleArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull double[] fieldValue); }### Answer: @Test public void testSerializeDoubleArray() { double[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getDoubleArray(randomKey())); }
### Question: ParcelableArrayCoder extends BaseCoder<Parcelable[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Parcelable[] fieldValue) { state.putParcelableArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Parcelable[] fieldValue); }### Answer: @Test public void testSerializeParcelableArray() { Parcelable[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getParcelableArray(randomKey())); }
### Question: LongCoder extends BaseCoder<Long> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Long fieldValue) { state.putLong(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Long fieldValue); }### Answer: @Test public void testSerializeLongPrimitive() { long expectedValue = 9L; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getLong(randomKey())); } @Test public void testSerializeLongObject() { Long expectedValue = 9L; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, ((Long) bundle().getLong(randomKey()))); }
### Question: Lyra { @NonNull public static String getKeyFromField(@NonNull Field field) { return field.getDeclaringClass().getName() + '#' + field.getName(); } @SuppressLint("NewApi") private Lyra(@NonNull Application application, @NonNull CoderRetriever coderRetriever, @NonNull FieldsRetriever fieldsRetriever, boolean autoSaveActivities); static Builder with(@NonNull Application application); @SuppressLint("NewApi") static void destroy(); static boolean isInitialized(); @NonNull static Lyra instance(); @NonNull static String getKeyFromField(@NonNull Field field); void saveState(@NonNull Object stateHolder, @NonNull Bundle state); void restoreState(@NonNull Object stateHolder, @Nullable Bundle state); Parcelable saveState(@NonNull View stateHolder, @Nullable Parcelable state); Parcelable restoreState(@NonNull View stateHolder, @Nullable Parcelable state); static final String SUB_BUNDLE_KEY; static final String VIEW_SUPER_STATE_BUNDLE_KEY; }### Answer: @Test public void testKeyFromFieldNotNull() { Field field = TestModels.MixedPublicFields.class.getDeclaredFields()[0]; assertNotNull(Lyra.getKeyFromField(field)); }
### Question: SerializableCoder extends BaseCoder<Serializable> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Serializable fieldValue) { state.putSerializable(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Serializable fieldValue); }### Answer: @Test public void testSerializeSerializable() { Serializable expectedValue = TestModels.ImplementedSerializable.getDefault(); mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getSerializable(randomKey())); }
### Question: BooleanCoder extends BaseCoder<Boolean> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Boolean fieldValue) { state.putBoolean(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Boolean fieldValue); }### Answer: @SuppressWarnings("ConstantConditions") @Test public void testSerializeBooleanPrimitive() { boolean expectedValue = true; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getBoolean(randomKey())); } @SuppressWarnings("ConstantConditions") @Test public void testSerializeBooleanObject() { Boolean expectedValue = true; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, ((Boolean) bundle().getBoolean(randomKey()))); }
### Question: ShortArrayCoder extends BaseCoder<short[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull short[] fieldValue) { state.putShortArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull short[] fieldValue); }### Answer: @Test public void testSerializeShortArray() { short[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getShortArray(randomKey())); }
### Question: FloatCoder extends BaseCoder<Float> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Float fieldValue) { state.putFloat(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Float fieldValue); }### Answer: @Test public void testSerializeFloatPrimitive() { float expectedValue = 9.0f; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getFloat(randomKey()), 0); } @Test public void testSerializeFloatObject() { Float expectedValue = 9.0f; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getFloat(randomKey())); }
### Question: ParcelableCoder extends BaseCoder<Parcelable> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Parcelable fieldValue) { state.putParcelable(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull Parcelable fieldValue); }### Answer: @Test public void testSerializeParcelable() { Parcelable expectedValue = TestModels.ImplementedParcelable.getDefault(); mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getParcelable(randomKey())); }
### Question: CharSequenceArrayCoder extends BaseCoder<CharSequence[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull CharSequence[] fieldValue) { state.putCharSequenceArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull CharSequence[] fieldValue); }### Answer: @Test public void testSerializeCharSequenceArray() { CharSequence[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getCharSequenceArray(randomKey())); }
### Question: CharSequenceCoder extends BaseCoder<CharSequence> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull CharSequence fieldValue) { state.putCharSequence(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull CharSequence fieldValue); }### Answer: @Test public void testSerializeCharSequence() { CharSequence expectedValue = "test"; mCoder.serialize(bundle(), randomKey(), expectedValue); assertEquals(expectedValue, bundle().getCharSequence(randomKey())); }
### Question: IntArrayCoder extends BaseCoder<int[]> { @Override public void serialize(@NonNull Bundle state, @NonNull String key, @NonNull int[] fieldValue) { state.putIntArray(key, fieldValue); } @Override void serialize(@NonNull Bundle state, @NonNull String key, @NonNull int[] fieldValue); }### Answer: @Test public void testSerializeIntArray() { int[] expected = generateArrayAndFill(); mCoder.serialize(bundle(), randomKey(), expected); assertEquals(expected, bundle().getIntArray(randomKey())); }
### Question: Tileset implements Disposable { public int getTileId(int x, int y) { return tilesetSource.getTileId(x, y, firstGid); } Tileset(int firstGid, TilesetSource tilesetSource); boolean containsProperty(String propertyName); String getProperty(String propertyName); void setProperty(String propertyName, String value); ObjectMap<String, String> getProperties(); void drawTile(Graphics g, int tileId, int renderX, int renderY); void drawTileset(Graphics g, int renderX, int renderY); Tile getTile(int tileId); Tile getTile(int x, int y); Array<AssetDescriptor> getDependencies(FileHandle tmxPath); boolean isTextureLoaded(); void loadTexture(FileHandle tmxPath); void loadTexture(AssetManager assetManager, FileHandle tmxPath); void loadTexture(TextureAtlas textureAtlas); @Override void dispose(); boolean contains(int tileId); int getTileId(int x, int y); int getTileX(int tileId); int getTileY(int tileId); int getWidthInTiles(); int getHeightInTiles(); int getWidth(); int getHeight(); int getTileWidth(); int getTileHeight(); int getSpacing(); int getMargin(); int getFirstGid(); String getSourceInternalUuid(); }### Answer: @Test public void testGetTileId() { tileset = new Tileset(1, new ImageTilesetSource(128, 128, 32, 32, 0, 0)); Assert.assertEquals(1, tileset.getTileId(0, 0)); Assert.assertEquals(5, tileset.getTileId(0, 1)); tileset = new Tileset(1, new ImageTilesetSource(1936, 1052, 32, 32, 2, 0)); Assert.assertEquals(1, tileset.getTileId(0, 0)); Assert.assertEquals(343, tileset.getTileId(0, 6)); Assert.assertEquals(345, tileset.getTileId(2, 6)); }
### Question: ConcurrentIntSet extends IntSet implements ConcurrentCollection { @Override public boolean remove(int key) { lock.lockWrite(); boolean b = super.remove(key); lock.unlockWrite(); return b; } ConcurrentIntSet(); ConcurrentIntSet(int initialCapacity); ConcurrentIntSet(int initialCapacity, float loadFactor); ConcurrentIntSet(IntSet set); @Override boolean add(int key); @Override void addAll(IntArray array, int offset, int length); @Override void addAll(int[] array, int offset, int length); @Override void addAll(IntSet set); @Override boolean remove(int key); @Override boolean notEmpty(); @Override boolean isEmpty(); @Override void shrink(int maximumCapacity); @Override void clear(int maximumCapacity); @Override void clear(); @Override boolean contains(int key); @Override int first(); @Override void ensureCapacity(int additionalCapacity); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override IntSetIterator iterator(); @Override ReadWriteLock getLock(); }### Answer: @Test public void testRemove(){ ConcurrentIntSet set = new ConcurrentIntSet(); for (int i = 0; i < 10000; i++) { set.add(i); } CountDownLatch latch = new CountDownLatch(1000); createStartAndJoinThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i < 10; i++) { set.lock.lockWrite(); int key = set.first(); assertTrue(set.contains(key)); set.remove(key); assertFalse(set.contains(key)); set.lock.unlockWrite(); } } }, 1000); assertEquals(0, set.size); }
### Question: ConcurrentOrderedSet extends OrderedSet<T> implements ConcurrentCollection { @Override public boolean add(T key) { lock.lockWrite(); boolean b = super.add(key); lock.unlockWrite(); return b; } ConcurrentOrderedSet(); ConcurrentOrderedSet(int initialCapacity); ConcurrentOrderedSet(int initialCapacity, float loadFactor); ConcurrentOrderedSet(OrderedSet<? extends T> set); @Override boolean add(T key); @Override void addAll(Array<? extends T> array, int offset, int length); @Override void addAll(T[] array, int offset, int length); @Override void addAll(ObjectSet<T> set); @Override boolean remove(T key); @Override boolean notEmpty(); @Override boolean isEmpty(); @Override void shrink(int maximumCapacity); @Override void clear(int maximumCapacity); @Override void clear(); @Override boolean contains(T key); @Override T get(T key); @Override T first(); @Override boolean add(T key, int index); @Override T removeIndex(int index); @Override Array<T> orderedItems(); @Override void ensureCapacity(int additionalCapacity); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override String toString(String separator); @Override OrderedSetIterator<T> iterator(); @Override ReadWriteLock getLock(); }### Answer: @Test public void testAdd() { ConcurrentOrderedSet<Integer> set = new ConcurrentOrderedSet<>(); Random r = new Random(); CountDownLatch latch = new CountDownLatch(1000); createStartAndJoinThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } while (!set.add(r.nextInt())){ } } }, 1000); assertEquals(1000, set.size); }
### Question: ConcurrentPooledLinkedList extends PooledLinkedList<T> implements ConcurrentCollection { @Override public void add(T object) { lock.lockWrite(); super.add(object); lock.unlockWrite(); } ConcurrentPooledLinkedList(int maxPoolSize); @Override void add(T object); @Override void addFirst(T object); @Override int size(); @Override void iter(); @Override void iterReverse(); @Override T next(); @Override T previous(); @Override void remove(); @Override T removeLast(); @Override void clear(); @Override ReadWriteLock getLock(); }### Answer: @Test public void testAdd() { ConcurrentPooledLinkedList<Integer> l = new ConcurrentPooledLinkedList<>(2000); l.iter(); CountDownLatch latch = new CountDownLatch(200); Thread[] addThread = createAndStartThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i < 10; i++) { l.add(i); } } }, 100); Thread[] addFirstThread = createAndStartThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i < 10; i++) { l.addFirst(i); } } }, 100); joinAll(addThread, addFirstThread); assertEquals(2000, l.size()); }
### Question: ConcurrentPooledLinkedList extends PooledLinkedList<T> implements ConcurrentCollection { @Override public void remove() { lock.lockWrite(); super.remove(); lock.unlockWrite(); } ConcurrentPooledLinkedList(int maxPoolSize); @Override void add(T object); @Override void addFirst(T object); @Override int size(); @Override void iter(); @Override void iterReverse(); @Override T next(); @Override T previous(); @Override void remove(); @Override T removeLast(); @Override void clear(); @Override ReadWriteLock getLock(); }### Answer: @Test public void testRemove() { ConcurrentPooledLinkedList<Integer> l = new ConcurrentPooledLinkedList<>(10000); for (int i = 0; i < 10000; i++) { l.addFirst(i); } l.iter(); CountDownLatch latch = new CountDownLatch(1000); Thread[] removeThread = createAndStartThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i < 10; i++) { l.lock.lockWrite(); l.next(); l.remove(); l.lock.unlockWrite(); } } }, 500); Thread[] removeLastThread = createAndStartThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i < 10; i++) { l.removeLast(); } } }, 500); joinAll(removeThread, removeLastThread); assertEquals(0, l.size()); }
### Question: ConcurrentObjectSet extends ObjectSet<T> implements ConcurrentCollection { @Override public boolean add(T key) { lock.lockWrite(); boolean b = super.add(key); lock.unlockWrite(); return b; } ConcurrentObjectSet(); ConcurrentObjectSet(int initialCapacity); ConcurrentObjectSet(int initialCapacity, float loadFactor); ConcurrentObjectSet(ObjectSet<? extends T> set); @Override boolean add(T key); @Override void addAll(Array<? extends T> array, int offset, int length); @Override void addAll(T[] array, int offset, int length); @Override void addAll(ObjectSet<T> set); @Override boolean remove(T key); @Override boolean notEmpty(); @Override boolean isEmpty(); @Override void shrink(int maximumCapacity); @Override void clear(int maximumCapacity); @Override void clear(); @Override boolean contains(T key); @Override T get(T key); @Override T first(); @Override void ensureCapacity(int additionalCapacity); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override String toString(String separator); @Override ObjectSetIterator<T> iterator(); @Override ReadWriteLock getLock(); }### Answer: @Test public void testAdd() { ConcurrentObjectSet<Integer> set = new ConcurrentObjectSet<>(); Random r = new Random(); CountDownLatch latch = new CountDownLatch(1000); createStartAndJoinThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } while (!set.add(r.nextInt())){ } } }, 1000); assertEquals(1000, set.size); }
### Question: ConcurrentObjectSet extends ObjectSet<T> implements ConcurrentCollection { @Override public boolean remove(T key) { lock.lockWrite(); boolean b = super.remove(key); lock.unlockWrite(); return b; } ConcurrentObjectSet(); ConcurrentObjectSet(int initialCapacity); ConcurrentObjectSet(int initialCapacity, float loadFactor); ConcurrentObjectSet(ObjectSet<? extends T> set); @Override boolean add(T key); @Override void addAll(Array<? extends T> array, int offset, int length); @Override void addAll(T[] array, int offset, int length); @Override void addAll(ObjectSet<T> set); @Override boolean remove(T key); @Override boolean notEmpty(); @Override boolean isEmpty(); @Override void shrink(int maximumCapacity); @Override void clear(int maximumCapacity); @Override void clear(); @Override boolean contains(T key); @Override T get(T key); @Override T first(); @Override void ensureCapacity(int additionalCapacity); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); @Override String toString(String separator); @Override ObjectSetIterator<T> iterator(); @Override ReadWriteLock getLock(); }### Answer: @Test public void testRemove(){ ConcurrentObjectSet<Integer> set = new ConcurrentObjectSet<>(); for (int i = 0; i < 10000; i++) { set.add(i); } CountDownLatch latch = new CountDownLatch(1000); createStartAndJoinThreads(new Runnable() { @Override public void run() { latch.countDown(); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } for (int i = 0; i < 10; i++) { set.lock.lockWrite(); int key = set.first(); assertTrue(set.contains(key)); set.remove(key); assertFalse(set.contains(key)); set.lock.unlockWrite(); } } }, 1000); assertEquals(0, set.size); }
### Question: LruObjectMap extends ObjectMap<K, V> { @Override public V put(K key, V value) { while(super.size >= maxCapacity) { purge(); } final V result = super.put(key, value); accessCounter.getAndIncrement(key, -1, 1); return result; } LruObjectMap(); LruObjectMap(int initialCapacity); LruObjectMap(int initialCapacity, float loadFactor); LruObjectMap(ObjectMap<? extends K, ? extends V> map); LruObjectMap(int initialCapacity, int maxCapacity); LruObjectMap(int initialCapacity, int maxCapacity, float loadFactor); LruObjectMap(ObjectMap<? extends K, ? extends V> map, int maxCapacity); @Override V put(K key, V value); @Override void putAll(ObjectMap<? extends K, ? extends V> map); @Override V get(K key); @Override V get(K key, V defaultValue); @Override V remove(K key); @Override void clear(); int getMaxCapacity(); static final int DEFAULT_MAX_CAPACITY; }### Answer: @Test public void testImmediatePurge() { for(int i = 0; i < MAX_CAPACITY; i++) { map.put("key" + i, "value" + i); } Assert.assertEquals(MAX_CAPACITY, map.size); for(int i = MAX_CAPACITY; i < MAX_CAPACITY * 2; i++) { map.put("key" + i, "value" + i); Assert.assertEquals(MAX_CAPACITY, map.size); } }
### Question: FloatQueue { public float removeLast () { if (size == 0) { throw new NoSuchElementException("Queue is empty."); } final float[] values = this.values; int tail = this.tail; tail--; if (tail == -1) { tail = values.length - 1; } final float result = values[tail]; this.tail = tail; size--; return result; } FloatQueue(); FloatQueue(int initialSize); void addLast(float object); void addFirst(float object); void ensureCapacity(int additional); float removeFirst(); float removeLast(); int indexOf(float value); boolean removeValue(float value); float removeIndex(int index); boolean notEmpty(); boolean isEmpty(); float first(); float last(); float get(int index); void clear(); Iterator<Float> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void removeLastTest() { FloatQueue queue = new FloatQueue(); queue.addLast((float) 1); queue.addLast((float) 2); queue.addLast((float) 3); queue.addLast((float) 4); assertEquals(4, queue.size); assertEquals(3, queue.indexOf((float) 4)); assertEquals(4, queue.removeLast(), 0.01); assertEquals(3, queue.size); assertEquals(2, queue.indexOf((float) 3)); assertEquals(3, queue.removeLast(), 0.01); assertEquals(2, queue.size); assertEquals(1, queue.indexOf((float) 2)); assertEquals(2, queue.removeLast(), 0.01); assertEquals(1, queue.size); assertEquals(0, queue.indexOf((float) 1)); assertEquals(1, queue.removeLast(), 0.01); assertEquals(0, queue.size); }
### Question: FloatQueue { public float removeFirst () { if (size == 0) { throw new NoSuchElementException("Queue is empty."); } final float[] values = this.values; final float result = values[head]; head++; if (head == values.length) { head = 0; } size--; return result; } FloatQueue(); FloatQueue(int initialSize); void addLast(float object); void addFirst(float object); void ensureCapacity(int additional); float removeFirst(); float removeLast(); int indexOf(float value); boolean removeValue(float value); float removeIndex(int index); boolean notEmpty(); boolean isEmpty(); float first(); float last(); float get(int index); void clear(); Iterator<Float> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void removeFirstTest() { FloatQueue queue = new FloatQueue(); queue.addLast((float) 1); queue.addLast((float) 2); queue.addLast((float) 3); queue.addLast((float) 4); assertEquals(4, queue.size); assertEquals(0, queue.indexOf((float) 1), 0.01); assertEquals(1, queue.removeFirst(), 0.01); assertEquals(3, queue.size); assertEquals(0, queue.indexOf((float) 2), 0.01); assertEquals(2, queue.removeFirst(), 0.01); assertEquals(2, queue.size); assertEquals(0, queue.indexOf((float) 3), 0.01); assertEquals(3, queue.removeFirst(), 0.01); assertEquals(1, queue.size); assertEquals(0, queue.indexOf((float) 4), 0.01); assertEquals(4, queue.removeFirst(), 0.01); assertEquals(0, queue.size); }
### Question: FloatQueue { public float get (int index) { if (index < 0) throw new IndexOutOfBoundsException("index can't be < 0: " + index); if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size); final float[] values = this.values; int i = head + index; if (i >= values.length) { i -= values.length; } return values[i]; } FloatQueue(); FloatQueue(int initialSize); void addLast(float object); void addFirst(float object); void ensureCapacity(int additional); float removeFirst(); float removeLast(); int indexOf(float value); boolean removeValue(float value); float removeIndex(int index); boolean notEmpty(); boolean isEmpty(); float first(); float last(); float get(int index); void clear(); Iterator<Float> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void getTest () { final FloatQueue q = new FloatQueue(7); for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { q.addLast((float) j); } assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first(), 0.01); assertEquals("get(size-1) is not equal to peekLast (" + i + ")", q.get(q.size - 1), q.last(), 0.01); for (int j = 0; j < 4; j++) { assertEquals(q.get(j), j, 0.0); } for (int j = 0; j < 4 - 1; j++) { q.removeFirst(); assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first(), 0.01); } q.removeFirst(); assert q.size == 0; try { q.get(0); fail("get() on empty queue did not throw"); } catch (IndexOutOfBoundsException ignore) { } } }
### Question: FloatQueue { public int indexOf (float value) { if (size == 0) return -1; float[] values = this.values; final int head = this.head, tail = this.tail; if (head < tail) { for (int i = head; i < tail; i++) if (values[i] == value) return i - head; } else { for (int i = head, n = values.length; i < n; i++) if (values[i] == value) return i - head; for (int i = 0; i < tail; i++) if (values[i] == value) return i + values.length - head; } return -1; } FloatQueue(); FloatQueue(int initialSize); void addLast(float object); void addFirst(float object); void ensureCapacity(int additional); float removeFirst(); float removeLast(); int indexOf(float value); boolean removeValue(float value); float removeIndex(int index); boolean notEmpty(); boolean isEmpty(); float first(); float last(); float get(int index); void clear(); Iterator<Float> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void indexOfTest () { final FloatQueue q = new FloatQueue(); for (int j = 0; j <= 6; j++) q.addLast((float) j); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf((float) j), j); q.clear(); for (int j = 2; j >= 0; j--) q.addFirst((float) j); for (int j = 3; j <= 6; j++) q.addLast((float) j); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf((float) j), j); }
### Question: FloatQueue { public String toString () { if (size == 0) { return "[]"; } final float[] values = this.values; final int head = this.head; final int tail = this.tail; StringBuilder sb = new StringBuilder(64); sb.append('['); sb.append(values[head]); for (int i = (head + 1) % values.length; i != tail; i = (i + 1) % values.length) { sb.append(", ").append(values[i]); } sb.append(']'); return sb.toString(); } FloatQueue(); FloatQueue(int initialSize); void addLast(float object); void addFirst(float object); void ensureCapacity(int additional); float removeFirst(); float removeLast(); int indexOf(float value); boolean removeValue(float value); float removeIndex(int index); boolean notEmpty(); boolean isEmpty(); float first(); float last(); float get(int index); void clear(); Iterator<Float> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void toStringTest () { FloatQueue q = new FloatQueue(1); assertEquals("[]", q.toString()); q.addLast((float) 4); assertEquals("[4.0]", q.toString()); q.addLast((float) 5); q.addLast((float) 6); q.addLast((float) 7); assertEquals("[4.0, 5.0, 6.0, 7.0]", q.toString()); }
### Question: CharQueue { public char removeLast () { if (size == 0) { throw new NoSuchElementException("Queue is empty."); } final char[] values = this.values; int tail = this.tail; tail--; if (tail == -1) { tail = values.length - 1; } final char result = values[tail]; this.tail = tail; size--; return result; } CharQueue(); CharQueue(int initialSize); void addLast(char object); void addFirst(char object); void ensureCapacity(int additional); char removeFirst(); char removeLast(); int indexOf(char value); boolean removeValue(char value); char removeIndex(int index); boolean notEmpty(); boolean isEmpty(); char first(); char last(); char get(int index); void clear(); Iterator<Character> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void removeLastTest() { CharQueue queue = new CharQueue(); queue.addLast((char) 1); queue.addLast((char) 2); queue.addLast((char) 3); queue.addLast((char) 4); assertEquals(4, queue.size); assertEquals(3, queue.indexOf((char) 4)); assertEquals((char) 4, queue.removeLast()); assertEquals(3, queue.size); assertEquals(2, queue.indexOf((char) 3)); assertEquals((char) 3, queue.removeLast()); assertEquals(2, queue.size); assertEquals(1, queue.indexOf((char) 2)); assertEquals((char) 2, queue.removeLast()); assertEquals(1, queue.size); assertEquals(0, queue.indexOf((char) 1)); assertEquals((char) 1, queue.removeLast()); assertEquals(0, queue.size); }
### Question: CharQueue { public char removeFirst () { if (size == 0) { throw new NoSuchElementException("Queue is empty."); } final char[] values = this.values; final char result = values[head]; head++; if (head == values.length) { head = 0; } size--; return result; } CharQueue(); CharQueue(int initialSize); void addLast(char object); void addFirst(char object); void ensureCapacity(int additional); char removeFirst(); char removeLast(); int indexOf(char value); boolean removeValue(char value); char removeIndex(int index); boolean notEmpty(); boolean isEmpty(); char first(); char last(); char get(int index); void clear(); Iterator<Character> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void removeFirstTest() { CharQueue queue = new CharQueue(); queue.addLast((char) 1); queue.addLast((char) 2); queue.addLast((char) 3); queue.addLast((char) 4); assertEquals(4, queue.size); assertEquals(0, queue.indexOf((char) 1)); assertEquals((char) 1, queue.removeFirst()); assertEquals(3, queue.size); assertEquals(0, queue.indexOf((char) 2)); assertEquals((char) 2, queue.removeFirst()); assertEquals(2, queue.size); assertEquals(0, queue.indexOf((char) 3)); assertEquals((char) 3, queue.removeFirst()); assertEquals(1, queue.size); assertEquals(0, queue.indexOf((char) 4)); assertEquals((char) 4, queue.removeFirst()); assertEquals(0, queue.size); }
### Question: CharQueue { public char get (int index) { if (index < 0) throw new IndexOutOfBoundsException("index can't be < 0: " + index); if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size); final char[] values = this.values; int i = head + index; if (i >= values.length) { i -= values.length; } return values[i]; } CharQueue(); CharQueue(int initialSize); void addLast(char object); void addFirst(char object); void ensureCapacity(int additional); char removeFirst(); char removeLast(); int indexOf(char value); boolean removeValue(char value); char removeIndex(int index); boolean notEmpty(); boolean isEmpty(); char first(); char last(); char get(int index); void clear(); Iterator<Character> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void getTest () { final CharQueue q = new CharQueue(7); for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { q.addLast((char) j); } assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first()); assertEquals("get(size-1) is not equal to peekLast (" + i + ")", q.get(q.size - 1), q.last()); for (int j = 0; j < 4; j++) { assertEquals(q.get(j), j); } for (int j = 0; j < 4 - 1; j++) { q.removeFirst(); assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first()); } q.removeFirst(); assert q.size == 0; try { q.get(0); fail("get() on empty queue did not throw"); } catch (IndexOutOfBoundsException ignore) { } } }
### Question: CharQueue { public int indexOf (char value) { if (size == 0) return -1; char[] values = this.values; final int head = this.head, tail = this.tail; if (head < tail) { for (int i = head; i < tail; i++) if (values[i] == value) return i - head; } else { for (int i = head, n = values.length; i < n; i++) if (values[i] == value) return i - head; for (int i = 0; i < tail; i++) if (values[i] == value) return i + values.length - head; } return -1; } CharQueue(); CharQueue(int initialSize); void addLast(char object); void addFirst(char object); void ensureCapacity(int additional); char removeFirst(); char removeLast(); int indexOf(char value); boolean removeValue(char value); char removeIndex(int index); boolean notEmpty(); boolean isEmpty(); char first(); char last(); char get(int index); void clear(); Iterator<Character> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void indexOfTest () { final CharQueue q = new CharQueue(); for (int j = 0; j <= 6; j++) q.addLast((char) j); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf((char) j), j); q.clear(); for (int j = 2; j >= 0; j--) q.addFirst((char) j); for (int j = 3; j <= 6; j++) q.addLast((char) j); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf((char) j), j); }
### Question: CharQueue { public String toString () { if (size == 0) { return "[]"; } final char[] values = this.values; final int head = this.head; final int tail = this.tail; StringBuilder sb = new StringBuilder(64); sb.append('['); sb.append(values[head]); for (int i = (head + 1) % values.length; i != tail; i = (i + 1) % values.length) { sb.append(", ").append(values[i]); } sb.append(']'); return sb.toString(); } CharQueue(); CharQueue(int initialSize); void addLast(char object); void addFirst(char object); void ensureCapacity(int additional); char removeFirst(); char removeLast(); int indexOf(char value); boolean removeValue(char value); char removeIndex(int index); boolean notEmpty(); boolean isEmpty(); char first(); char last(); char get(int index); void clear(); Iterator<Character> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void toStringTest () { CharQueue q = new CharQueue(1); assertEquals("[]", q.toString()); q.addLast((char) 4); assertEquals(q.toString(), "[" + '\4' + "]"); q.addLast((char) 5); q.addLast((char) 6); q.addLast((char) 7); assertEquals(q.toString(), "[" + '\4' + ", " + '\5' + ", " + '\6' + ", " + '\7' + "]"); }
### Question: RenderPipeline { public void update(GameContainer gc, float delta) { for(RenderOperation stage : operations) { stage.update(gc, delta); } } RenderPipeline(); void update(GameContainer gc, float delta); void interpolate(GameContainer gc, float alpha); void render(GameContainer gc, Graphics g); void add(RenderOperation operation); void remove(RenderOperation operation); boolean isOneWay(); void setOneWay(boolean oneWay); }### Answer: @Test public void testPipelineUpdate() { final float delta = 1.0f; mockery.checking(new Expectations() { { oneOf(operation1).update(gc, delta); oneOf(operation2).update(gc, delta); } }); pipeline.update(gc, delta); }
### Question: RenderPipeline { public void interpolate(GameContainer gc, float alpha) { for(RenderOperation stage : operations) { stage.interpolate(gc, alpha); } } RenderPipeline(); void update(GameContainer gc, float delta); void interpolate(GameContainer gc, float alpha); void render(GameContainer gc, Graphics g); void add(RenderOperation operation); void remove(RenderOperation operation); boolean isOneWay(); void setOneWay(boolean oneWay); }### Answer: @Test public void testPipelineInterpolate() { final float alpha = 1.0f; mockery.checking(new Expectations() { { oneOf(operation1).interpolate(gc, alpha); oneOf(operation2).interpolate(gc, alpha); } }); pipeline.interpolate(gc, alpha); }
### Question: RenderPipeline { public void render(GameContainer gc, Graphics g) { for(RenderOperation stage : operations) { stage.apply(gc, g); } if(oneWay) { return; } for(int i = operations.size - 1; i >= 0; i--) { operations.get(i).unapply(gc, g); } } RenderPipeline(); void update(GameContainer gc, float delta); void interpolate(GameContainer gc, float alpha); void render(GameContainer gc, Graphics g); void add(RenderOperation operation); void remove(RenderOperation operation); boolean isOneWay(); void setOneWay(boolean oneWay); }### Answer: @Test public void testDefaultPipeline() { final Sequence invokeSequence = mockery.sequence("sequence-name"); mockery.checking(new Expectations() { { oneOf(operation1).apply(gc, g); inSequence(invokeSequence); oneOf(operation2).apply(gc, g); inSequence(invokeSequence); oneOf(operation2).unapply(gc, g); inSequence(invokeSequence); oneOf(operation1).unapply(gc, g); inSequence(invokeSequence); } }); pipeline.render(gc, g); }
### Question: TiledObjectTemplate { public TiledObjectTemplate(String path, Tileset tileset, TiledObject tiledObject) { super(); this.path = path; this.tileset = tileset; this.tiledObject = tiledObject; } TiledObjectTemplate(String path, Tileset tileset, TiledObject tiledObject); String getPath(); Tileset getTileset(); TiledObject getTiledObject(); }### Answer: @Test public void testTiledObjectTemplate() throws TiledException { final String objectGroupName = "Objects"; final String propertyName = "testProperty"; Assert.assertEquals(1, tiledMap.getTilesets().size); final TiledObject templateObject = tiledMap.getObjectGroup(objectGroupName).getObjectById(3); Assert.assertEquals("SUCCESS", templateObject.getProperty(propertyName)); final TiledObject overrideTemplateObject = tiledMap.getObjectGroup(objectGroupName).getObjectById(4); Assert.assertEquals("FAILED", overrideTemplateObject.getProperty(propertyName)); Assert.assertEquals(1, TiledMapData.OBJECT_TEMPLATE_TILESET_SOURCES.size); }
### Question: CollisionCircle extends Circle implements CollisionArea, PositionChangeListener<CollisionCircle>, SizeChangeListener<CollisionCircle> { @Override public int getId() { return id; } CollisionCircle(float radius); CollisionCircle(int id, float radius); CollisionCircle(float centerX, float centerY, float radius); CollisionCircle(int id, float centerX, float centerY, float radius); CollisionCircle(int id, Collisions collisions); @Override void dispose(); @Override void preUpdate(); @Override void interpolate(float alpha); @Override CollisionArea setTo(float x, float y, float width, float height); @Override void forceTo(float x, float y, float width, float height); @Override void forceToWidth(float width); @Override void forceToHeight(float height); @Override void forceTo(float x, float y); @Override int getId(); @Override int getRenderX(); @Override int getRenderY(); @Override float getRawRenderX(); @Override float getRawRenderY(); @Override RenderCoordMode getRenderCoordMode(); @Override void setRenderCoordMode(RenderCoordMode mode); @Override int getRenderWidth(); @Override int getRenderHeight(); @Override float getRawRenderWidth(); @Override float getRawRenderHeight(); int getRenderRadius(); float getRawRenderRadius(); @Override void positionChanged(CollisionCircle moved); @Override void sizeChanged(CollisionCircle changed); @Override void addPostionChangeListener( PositionChangeListener<T> listener); @Override void removePositionChangeListener( PositionChangeListener<T> listener); @Override void addSizeChangeListener(SizeChangeListener<T> listener); @Override void removeSizeChangeListener(SizeChangeListener<T> listener); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testIdGeneration() { CollisionCircle circle2 = new CollisionCircle(20f, 20f, 4); Assert.assertEquals(true, circle.getId() != circle2.getId()); }
### Question: CollisionPoint extends Point implements CollisionObject, PositionChangeListener<CollisionPoint> { @Override public int getId() { return id; } CollisionPoint(); CollisionPoint(int id); CollisionPoint(float x, float y); CollisionPoint(int id, float x, float y); CollisionPoint(int id, Collisions collisions); @Override void dispose(); @Override void preUpdate(); @Override void interpolate(float alpha); @Override void forceTo(float x, float y); @Override int getRenderX(); @Override int getRenderY(); @Override float getRawRenderX(); @Override float getRawRenderY(); @Override RenderCoordMode getRenderCoordMode(); @Override void setRenderCoordMode(RenderCoordMode mode); @Override int getId(); @Override void positionChanged(CollisionPoint moved); @Override void addPostionChangeListener( PositionChangeListener<T> listener); @Override void removePositionChangeListener( PositionChangeListener<T> listener); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testIdGeneration() { Assert.assertEquals(true, point1.getId() != point2.getId()); Assert.assertEquals(true, point1.getId() != point3.getId()); Assert.assertEquals(true, point2.getId() != point3.getId()); }
### Question: CollisionBox extends Rectangle implements CollisionArea, PositionChangeListener<CollisionBox>, SizeChangeListener<CollisionBox> { @Override public int getId() { return id; } CollisionBox(); CollisionBox(int id); CollisionBox(float x, float y, float width, float height); CollisionBox(int id, float x, float y, float width, float height); CollisionBox(int id, Collisions collisions); @Override void dispose(); @Override void forceTo(float x, float y); @Override CollisionArea setTo(float x, float y, float width, float height); @Override void forceTo(float x, float y, float width, float height); void forceToWidth(float width); void forceToHeight(float height); @Override int getRenderWidth(); @Override int getRenderHeight(); @Override float getRawRenderWidth(); @Override float getRawRenderHeight(); @Override void preUpdate(); @Override void interpolate(float alpha); @Override int getRenderX(); @Override int getRenderY(); @Override float getRawRenderX(); @Override float getRawRenderY(); @Override RenderCoordMode getRenderCoordMode(); @Override void setRenderCoordMode(RenderCoordMode mode); @Override int getId(); @Override void positionChanged(CollisionBox moved); @Override void sizeChanged(CollisionBox changed); @Override void addPostionChangeListener( PositionChangeListener<T> listener); @Override void removePositionChangeListener( PositionChangeListener<T> listener); @Override void addSizeChangeListener(SizeChangeListener<T> listener); @Override void removeSizeChangeListener(SizeChangeListener<T> listener); boolean isInterpolateRequired(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testIdGeneration() { rectangle1 = new CollisionBox(); rectangle2 = new CollisionBox(); Assert.assertEquals(true, rectangle1.getId() != rectangle2.getId()); }
### Question: Tileset implements Disposable { public boolean contains(int tileId) { return tilesetSource.contains(tileId, firstGid, lastGid); } Tileset(int firstGid, TilesetSource tilesetSource); boolean containsProperty(String propertyName); String getProperty(String propertyName); void setProperty(String propertyName, String value); ObjectMap<String, String> getProperties(); void drawTile(Graphics g, int tileId, int renderX, int renderY); void drawTileset(Graphics g, int renderX, int renderY); Tile getTile(int tileId); Tile getTile(int x, int y); Array<AssetDescriptor> getDependencies(FileHandle tmxPath); boolean isTextureLoaded(); void loadTexture(FileHandle tmxPath); void loadTexture(AssetManager assetManager, FileHandle tmxPath); void loadTexture(TextureAtlas textureAtlas); @Override void dispose(); boolean contains(int tileId); int getTileId(int x, int y); int getTileX(int tileId); int getTileY(int tileId); int getWidthInTiles(); int getHeightInTiles(); int getWidth(); int getHeight(); int getTileWidth(); int getTileHeight(); int getSpacing(); int getMargin(); int getFirstGid(); String getSourceInternalUuid(); }### Answer: @Test public void testLastGidWithoutSpacing() { tileset = new Tileset(1, new ImageTilesetSource(128, 128, 32, 32, 0, 0)); Assert.assertEquals(true, tileset.contains(16)); Assert.assertEquals(false, tileset.contains(17)); } @Test public void testLastGidWithSpacing() { tileset = new Tileset(1, new ImageTilesetSource(128, 128, 32, 32, 4, 0)); Assert.assertEquals(true, tileset.contains(9)); Assert.assertEquals(false, tileset.contains(10)); }
### Question: RegularHexagon extends RegularPolygon { @Override public void dispose() { if(disposed) { return; } disposed = true; clearPositionChangeListeners(); clearSizeChangeListeners(); if(geometry == null) { return; } geometry.release(this); } RegularHexagon(float centerX, float centerY, float radius); RegularHexagon(Geometry geometry); @Override void dispose(); static final float ROTATION_SYMMETRY; }### Answer: @Test public void testDispose() { Geometry.DEFAULT_POOL_SIZE = 1; Geometry geometry = new Geometry(); org.junit.Assert.assertEquals(1, geometry.getTotalRegularHexagonsAvailable()); RegularHexagon hexagon = geometry.regularHexagon(); org.junit.Assert.assertEquals(0, geometry.getTotalRegularHexagonsAvailable()); hexagon.dispose(); org.junit.Assert.assertEquals(1, geometry.getTotalRegularHexagonsAvailable()); hexagon.dispose(); org.junit.Assert.assertEquals(1, geometry.getTotalRegularHexagonsAvailable()); hexagon = geometry.regularHexagon(); org.junit.Assert.assertEquals(0, geometry.getTotalRegularHexagonsAvailable()); hexagon.dispose(); org.junit.Assert.assertEquals(1, geometry.getTotalRegularHexagonsAvailable()); }
### Question: LineSegment implements Disposable { public void set(float x1, float y1, float x2, float y2) { pointA.set(x1, y1); pointB.set(x2, y2); } LineSegment(Geometry geometry); LineSegment(float x1, float y1, float x2, float y2); LineSegment(Point pA, Point pB); void dispose(); void setDisposed(boolean disposed); void set(float x1, float y1, float x2, float y2); boolean contains(float x, float y); boolean intersectsLineSegment(float segmentX1, float segmentY1, float segmentX2, float segmentY2); boolean intersects(LineSegment lineSegment); @Deprecated Point getIntersection(LineSegment lineSegment); boolean getIntersection(LineSegment lineSegment, Point result); boolean intersects(Rectangle rectangle); Point getPointA(); void setPointA(Point pointA); Point getPointB(); void setPointB(Point pointB); float getMinX(); float getMinY(); float getMaxX(); float getMaxY(); float getLength(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testSet() { segment1 = new LineSegment(0, 0, 10, 10); segment1.set(15, 17, 25, 27); Assert.assertEquals(15f, segment1.getPointA().x, 0f); Assert.assertEquals(17f, segment1.getPointA().y, 0f); Assert.assertEquals(25f, segment1.getPointB().x, 0f); Assert.assertEquals(27f, segment1.getPointB().y, 0f); }
### Question: LineSegment implements Disposable { public boolean contains(float x, float y) { if (pointA.getX() == x && pointA.getY() == y) return true; if (pointB.getX() == x && pointB.getY() == y) return true; Point p3 = new Point(x, y); return p3.isOnLineBetween(pointA, pointB); } LineSegment(Geometry geometry); LineSegment(float x1, float y1, float x2, float y2); LineSegment(Point pA, Point pB); void dispose(); void setDisposed(boolean disposed); void set(float x1, float y1, float x2, float y2); boolean contains(float x, float y); boolean intersectsLineSegment(float segmentX1, float segmentY1, float segmentX2, float segmentY2); boolean intersects(LineSegment lineSegment); @Deprecated Point getIntersection(LineSegment lineSegment); boolean getIntersection(LineSegment lineSegment, Point result); boolean intersects(Rectangle rectangle); Point getPointA(); void setPointA(Point pointA); Point getPointB(); void setPointB(Point pointB); float getMinX(); float getMinY(); float getMaxX(); float getMaxY(); float getLength(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testContains() { segment1 = new LineSegment(0, 0, 10, 0); Assert.assertEquals(true, segment1.contains(0, 0)); Assert.assertEquals(true, segment1.contains(10, 0)); Assert.assertEquals(true, segment1.contains(5, 0)); Assert.assertEquals(false, segment1.contains(5, -5)); Assert.assertEquals(false, segment1.contains(5, 5)); Assert.assertEquals(false, segment1.contains(-5, -5)); Assert.assertEquals(false, segment1.contains(15, -5)); Assert.assertEquals(false, segment1.contains(-5, 5)); Assert.assertEquals(false, segment1.contains(15, 5)); }
### Question: LineSegment implements Disposable { public boolean intersectsLineSegment(float segmentX1, float segmentY1, float segmentX2, float segmentY2) { return Intersector.intersectLineSegments(pointA.x, pointA.y, pointB.x, pointB.y, segmentX1, segmentY1, segmentX2, segmentY2); } LineSegment(Geometry geometry); LineSegment(float x1, float y1, float x2, float y2); LineSegment(Point pA, Point pB); void dispose(); void setDisposed(boolean disposed); void set(float x1, float y1, float x2, float y2); boolean contains(float x, float y); boolean intersectsLineSegment(float segmentX1, float segmentY1, float segmentX2, float segmentY2); boolean intersects(LineSegment lineSegment); @Deprecated Point getIntersection(LineSegment lineSegment); boolean getIntersection(LineSegment lineSegment, Point result); boolean intersects(Rectangle rectangle); Point getPointA(); void setPointA(Point pointA); Point getPointB(); void setPointB(Point pointB); float getMinX(); float getMinY(); float getMaxX(); float getMaxY(); float getLength(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testIntersectsLineSegment() { segment1 = new LineSegment(0, 0, 10, 0); segment2 = new LineSegment(5, -5, 5, 5); Assert.assertEquals(true, segment1.intersects(segment2)); Assert.assertEquals(true, segment2.intersects(segment1)); segment2 = new LineSegment(15, -5, 15, 5); Assert.assertEquals(false, segment1.intersects(segment2)); Assert.assertEquals(false, segment2.intersects(segment1)); }
### Question: LineSegment implements Disposable { public void dispose() { if(disposed) { return; } disposed = true; if(geometry == null) { return; } geometry.release(this); } LineSegment(Geometry geometry); LineSegment(float x1, float y1, float x2, float y2); LineSegment(Point pA, Point pB); void dispose(); void setDisposed(boolean disposed); void set(float x1, float y1, float x2, float y2); boolean contains(float x, float y); boolean intersectsLineSegment(float segmentX1, float segmentY1, float segmentX2, float segmentY2); boolean intersects(LineSegment lineSegment); @Deprecated Point getIntersection(LineSegment lineSegment); boolean getIntersection(LineSegment lineSegment, Point result); boolean intersects(Rectangle rectangle); Point getPointA(); void setPointA(Point pointA); Point getPointB(); void setPointB(Point pointB); float getMinX(); float getMinY(); float getMaxX(); float getMaxY(); float getLength(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testDispose() { Geometry.DEFAULT_POOL_SIZE = 1; Geometry geometry = new Geometry(); org.junit.Assert.assertEquals(1, geometry.getTotalLineSegmentsAvailable()); segment1 = geometry.lineSegment(); org.junit.Assert.assertEquals(0, geometry.getTotalLineSegmentsAvailable()); segment1.dispose(); org.junit.Assert.assertEquals(1, geometry.getTotalLineSegmentsAvailable()); segment1.dispose(); org.junit.Assert.assertEquals(1, geometry.getTotalLineSegmentsAvailable()); segment1 = geometry.lineSegment(); org.junit.Assert.assertEquals(0, geometry.getTotalLineSegmentsAvailable()); segment1.dispose(); org.junit.Assert.assertEquals(1, geometry.getTotalLineSegmentsAvailable()); }
### Question: RegularPentagon extends RegularPolygon { @Override public void dispose() { if(disposed) { return; } disposed = true; clearPositionChangeListeners(); clearSizeChangeListeners(); if(geometry == null) { return; } geometry.release(this); } RegularPentagon(float centerX, float centerY, float radius); RegularPentagon(Geometry geometry); @Override void dispose(); static final float ROTATION_SYMMETRY; }### Answer: @Test public void testDispose() { Geometry.DEFAULT_POOL_SIZE = 1; Geometry geometry = new Geometry(); org.junit.Assert.assertEquals(1, geometry.getTotalRegularPentagonsAvailable()); RegularPentagon pentagon = geometry.regularPentagon(); org.junit.Assert.assertEquals(0, geometry.getTotalRegularPentagonsAvailable()); pentagon.dispose(); org.junit.Assert.assertEquals(1, geometry.getTotalRegularPentagonsAvailable()); pentagon.dispose(); org.junit.Assert.assertEquals(1, geometry.getTotalRegularPentagonsAvailable()); pentagon = geometry.regularPentagon(); org.junit.Assert.assertEquals(0, geometry.getTotalRegularPentagonsAvailable()); pentagon.dispose(); org.junit.Assert.assertEquals(1, geometry.getTotalRegularPentagonsAvailable()); }
### Question: RenderingEntitySystem extends EntitySystem implements RenderingSystem { protected abstract void render(int entityId, Graphics g); RenderingEntitySystem(Builder aspect); @Override void renderSystem(Graphics g); @Override void setWorld(World world); }### Answer: @Test public void testRenderMatchesEntities() { Entity entityWithComponent = world.createEntity(); entityWithComponent.edit().add(new DummyComponent()); Entity entityWithoutComponent = world.createEntity(); world.process(); world.render(graphics); Assert.assertEquals(true, renderedIds.contains(entityWithComponent.getId())); Assert.assertEquals(false, renderedIds.contains(entityWithoutComponent.getId())); } @Test public void testRenderPassesGraphicsInstance() { Entity entityWithComponent = world.createEntity(); entityWithComponent.edit().add(new DummyComponent()); world.process(); world.render(graphics); } @Test public void testRenderDoesNothingIfCalledBeforeFirstProcess() { Entity entityWithComponent = world.createEntity(); entityWithComponent.edit().add(new DummyComponent()); world.render(graphics); }
### Question: UiXmlLoader { public <T extends UiElement> T load(String filename) { try { Reader reader = fileHandleResolver.resolve(filename).reader(); XmlReader xmlReader = new XmlReader(); XmlReader.Element root = xmlReader.parse(reader); return (T) processXmlTag(root); } catch (Exception e) { throw new MdxException("Failed to load UI file: " + filename, e); } } UiXmlLoader(FileHandleResolver fileHandleResolver); void addTagHandler(String tagName, UiElementFactory factory, UiElementPopulator... populators); T load(String filename); T load(String filename, Class<T> model); T load(String filename, T model); }### Answer: @Test public void fail_to_parse_file_contents() { String badFileFormat = "{\"hello\": \"world\"}"; FileHandle fileHandle = mockery.mock(FileHandle.class); mockery.checking(new Expectations() { { oneOf(fileHandleResolver).resolve(filename); try { oneOf(fileHandle).reader(); will(returnValue(new StringReader(badFileFormat))); } catch (IOException e) { throw new RuntimeException(e); } } }); try { loader.load(filename); fail(); } catch (Exception e) { assertEquals("Failed to load UI file: " + filename, e.getMessage()); assertNotNull(e.getCause()); } } @Test public void fail_to_resolve_file() { RuntimeException realError = new RuntimeException("BOOM"); mockery.checking(new Expectations() { { oneOf(fileHandleResolver).resolve(filename); will(throwException(realError)); } }); try { loader.load(filename); fail(); } catch (Exception e) { assertEquals("Failed to load UI file: " + filename, e.getMessage()); assertSame(e.getCause(), realError); } }
### Question: XmlTagUtil { public static String getTagNameWithoutPrefix(XmlReader.Element element) { return element.getName().replaceAll("(.*?:)?(.+?)", "$2"); } static String getTagNameWithoutPrefix(XmlReader.Element element); }### Answer: @Test public void with_prefix() { XmlReader.Element element = new XmlReader.Element("ui:text", null); assertEquals("text", getTagNameWithoutPrefix(element)); } @Test public void no_prefix() { XmlReader.Element element = new XmlReader.Element("text", null); assertEquals("text", getTagNameWithoutPrefix(element)); }
### Question: XmlAttributeMapper { public static Visibility mapToVisibility(XmlReader.Element element, String attributeName) { String providedValue = element.getAttribute(attributeName, "VISIBLE"); try { return Visibility.valueOf(providedValue.toUpperCase()); } catch (IllegalArgumentException e) { throw new InvalidVisibilityException(element, providedValue); } } static FlexDirection mapToFlexDirection(XmlReader.Element element); static Visibility mapToVisibility(XmlReader.Element element, String attributeName); }### Answer: @Test public void mapToVisibility_unknown_visibility() { tag.setAttribute("visibility", "does-not-exist"); try { XmlAttributeMapper.mapToVisibility(tag, "visibility"); fail(); } catch (InvalidVisibilityException e) { assertTrue(e.getMessage().startsWith("tag-name has an invalid value: does-not-exist")); } }
### Question: XmlAttributeMapper { public static FlexDirection mapToFlexDirection(XmlReader.Element element) { String value = element.getAttribute("flex-direction"); try { return FlexDirection.valueOf(value.toUpperCase()); } catch (IllegalArgumentException e) { throw new InvalidFlexDirectionException(element, value); } } static FlexDirection mapToFlexDirection(XmlReader.Element element); static Visibility mapToVisibility(XmlReader.Element element, String attributeName); }### Answer: @Test public void mapToFlexDirection_unsupported_flex_direction() { tag.setAttribute("flex-direction", "does-not-exist"); try { mapToFlexDirection(tag); fail(); } catch (InvalidFlexDirectionException e) { assertTrue(e.getMessage().startsWith("tag-name has an invalid value: does-not-exist")); } } @Test public void mapToFlexDirection_flex_directions_case_insensitive() { tag.setAttribute("flex-direction", "ColUmn"); assertEquals(COLUMN, mapToFlexDirection(tag)); } @Test public void mapToFlexDirection_all_directions() { for (FlexDirection value : values()) { tag.setAttribute("flex-direction", value.name()); assertEquals(value, mapToFlexDirection(tag)); } }
### Question: LabelPopulator implements UiElementPopulator<Label> { @Override public boolean populate(XmlReader.Element xmlTag, Label uiElement) { if (xmlTag.hasAttribute("text")) { uiElement.setText(xmlTag.getAttribute("text")); } uiElement.setResponsive(xmlTag.getBoolean("responsive", false)); String providedHorizontalAlignment = xmlTag.get("horizontal-alignment", "LEFT").toUpperCase(); uiElement.setHorizontalAlignment(HorizontalAlignment.valueOf(providedHorizontalAlignment)); return false; } @Override boolean populate(XmlReader.Element xmlTag, Label uiElement); }### Answer: @Test public void responsive_is_provided() { xmlTag.setAttribute("responsive", "true"); populator.populate(xmlTag, label); assertTrue(label.isResponsive()); } @Test public void responsive_is_defaulted_to_false() { populator.populate(xmlTag, label); assertFalse(label.isResponsive()); } @Test public void horizontal_alignment_case_does_not_matter() { xmlTag.setAttribute("horizontal-alignment", "center"); populator.populate(xmlTag, label); assertEquals(CENTER, label.getHorizontalAlignment()); } @Test public void horizontal_alignment_CENTER() { xmlTag.setAttribute("horizontal-alignment", "CENTER"); populator.populate(xmlTag, label); assertEquals(CENTER, label.getHorizontalAlignment()); } @Test public void horizontal_alignment_RIGHT() { xmlTag.setAttribute("horizontal-alignment", "RIGHT"); populator.populate(xmlTag, label); assertEquals(RIGHT, label.getHorizontalAlignment()); } @Test public void default_horizontal_alignment() { populator.populate(xmlTag, label); assertEquals(LEFT, label.getHorizontalAlignment()); } @Test public void text_provided() { xmlTag.setAttribute("text", "hello"); populator.populate(xmlTag, label); assertEquals("hello", label.getText()); } @Test public void no_text_provided() { populator.populate(xmlTag, label); assertEquals("", label.getText()); }
### Question: GridUiNavigation implements UiNavigation { public Actionable get(int x, int y) { return navigation.get(getIndex(x, y)); } GridUiNavigation(int xsColumns); @Override void layout(ScreenSize screenSize); @Override void add(Actionable actionable); @Override void remove(Actionable actionable); @Override void removeAll(); @Override void set(int index, Actionable actionable); Actionable get(int x, int y); void set(int x, int y, Actionable actionable); @Override Actionable navigate(int keycode); @Override Actionable getCursor(); @Override Actionable resetCursor(); @Override Actionable resetCursor(boolean triggerHoverEvent); void setWidth(ScreenSize screenSize, int columns); int getTotalColumns(); int getTotalRows(); @Override String toString(); @Override void onHoverBegin(Hoverable source); @Override void onHoverEnd(Hoverable source); }### Answer: @Test public void testSetXY() { addElementsToGrid(); for(int x = 0; x < COLUMNS; x++) { for(int y = 0; y < ROWS; y++) { Assert.assertEquals(elements[x][y], navigation.get(x, y)); } } }
### Question: PowerOfTwo { public static int nextPowerOfTwo(int value) { return MathUtils.nextPowerOfTwo(value); } static int nextPowerOfTwo(int value); static int previousPowerOfTwo(int value); }### Answer: @Test public void testNextPowerOfTwo() { for(int power = 1; power < 16; power++) { for(int i = (int) Math.pow(2, power) + 1; i <= (int) Math.pow(2, power); i++) { Assert.assertEquals((int) Math.pow(2, power), PowerOfTwo.nextPowerOfTwo(i)); } } }
### Question: PowerOfTwo { public static int previousPowerOfTwo(int value) { final int power = (int)(Math.log(value) / Math.log(2)); return (int) Math.pow(2, power); } static int nextPowerOfTwo(int value); static int previousPowerOfTwo(int value); }### Answer: @Test public void testPreviousPowerOfTwo() { for(int power = 16; power > 0; power--) { for(int i = (int) Math.pow(2, power) - 1; i >= (int) Math.pow(2, power - 1); i--) { Assert.assertEquals((int) Math.pow(2, power - 1), PowerOfTwo.previousPowerOfTwo(i)); } } Assert.assertEquals(1, PowerOfTwo.previousPowerOfTwo(1)); }
### Question: BooleanQueue { public boolean removeLast () { if (size == 0) { throw new NoSuchElementException("Queue is empty."); } final boolean[] values = this.values; int tail = this.tail; tail--; if (tail == -1) { tail = values.length - 1; } final boolean result = values[tail]; this.tail = tail; size--; return result; } BooleanQueue(); BooleanQueue(int initialSize); void addLast(boolean object); void addFirst(boolean object); void ensureCapacity(int additional); boolean removeFirst(); boolean removeLast(); int indexOf(boolean value); boolean removeValue(boolean value); boolean removeIndex(int index); boolean notEmpty(); boolean isEmpty(); boolean first(); boolean last(); boolean get(int index); void clear(); Iterator<Boolean> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void removeLastTest() { BooleanQueue queue = new BooleanQueue(); queue.addLast(true); queue.addLast(false); queue.addLast(true); queue.addLast(false); assertEquals(4, queue.size); assertFalse(queue.removeLast()); assertEquals(3, queue.size); assertTrue(queue.removeLast()); assertEquals(2, queue.size); assertFalse(queue.removeLast()); assertEquals(1, queue.size); assertTrue(queue.removeLast()); assertEquals(0, queue.size); }
### Question: BooleanQueue { public boolean removeFirst () { if (size == 0) { throw new NoSuchElementException("Queue is empty."); } final boolean[] values = this.values; final boolean result = values[head]; head++; if (head == values.length) { head = 0; } size--; return result; } BooleanQueue(); BooleanQueue(int initialSize); void addLast(boolean object); void addFirst(boolean object); void ensureCapacity(int additional); boolean removeFirst(); boolean removeLast(); int indexOf(boolean value); boolean removeValue(boolean value); boolean removeIndex(int index); boolean notEmpty(); boolean isEmpty(); boolean first(); boolean last(); boolean get(int index); void clear(); Iterator<Boolean> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void removeFirstTest() { BooleanQueue queue = new BooleanQueue(); queue.addLast(false); queue.addLast(true); queue.addLast(false); queue.addLast(true); assertEquals(4, queue.size); assertFalse(queue.removeFirst()); assertEquals(3, queue.size); assertTrue(queue.removeFirst()); assertEquals(2, queue.size); assertFalse(queue.removeFirst()); assertEquals(1, queue.size); assertTrue(queue.removeFirst()); assertEquals(0, queue.size); }
### Question: BooleanQueue { public boolean get (int index) { if (index < 0) throw new IndexOutOfBoundsException("index can't be < 0: " + index); if (index >= size) throw new IndexOutOfBoundsException("index can't be >= size: " + index + " >= " + size); final boolean[] values = this.values; int i = head + index; if (i >= values.length) { i -= values.length; } return values[i]; } BooleanQueue(); BooleanQueue(int initialSize); void addLast(boolean object); void addFirst(boolean object); void ensureCapacity(int additional); boolean removeFirst(); boolean removeLast(); int indexOf(boolean value); boolean removeValue(boolean value); boolean removeIndex(int index); boolean notEmpty(); boolean isEmpty(); boolean first(); boolean last(); boolean get(int index); void clear(); Iterator<Boolean> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void getTest () { final BooleanQueue q = new BooleanQueue(7); for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { q.addLast(j % 2 == 0); } assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first()); assertEquals("get(size-1) is not equal to peekLast (" + i + ")", q.get(q.size - 1), q.last()); for (int j = 0; j < 4; j++) { assertEquals(q.get(j), (j % 2 == 0)); } for (int j = 0; j < 4 - 1; j++) { q.removeFirst(); assertEquals("get(0) is not equal to peek (" + i + ")", q.get(0), q.first()); } q.removeFirst(); assert q.size == 0; try { q.get(0); fail("get() on empty queue did not throw"); } catch (IndexOutOfBoundsException ignore) { } } }
### Question: BooleanQueue { public int indexOf (boolean value) { if (size == 0) return -1; boolean[] values = this.values; final int head = this.head, tail = this.tail; if (head < tail) { for (int i = head; i < tail; i++) if (values[i] == value) return i - head; } else { for (int i = head, n = values.length; i < n; i++) if (values[i] == value) return i - head; for (int i = 0; i < tail; i++) if (values[i] == value) return i + values.length - head; } return -1; } BooleanQueue(); BooleanQueue(int initialSize); void addLast(boolean object); void addFirst(boolean object); void ensureCapacity(int additional); boolean removeFirst(); boolean removeLast(); int indexOf(boolean value); boolean removeValue(boolean value); boolean removeIndex(int index); boolean notEmpty(); boolean isEmpty(); boolean first(); boolean last(); boolean get(int index); void clear(); Iterator<Boolean> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void indexOfTest () { final BooleanQueue q = new BooleanQueue(); for (int j = 0; j <= 6; j++) q.addLast(j % 2 == 0); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf(j % 2 == 0), j % 2); q.clear(); for (int j = 2; j >= 0; j--) q.addFirst(j % 2 == 0); for (int j = 3; j <= 6; j++) q.addLast(j % 2 == 0); for (int j = 0; j <= 6; j++) assertEquals(q.indexOf(j % 2 == 0), j % 2); }
### Question: BooleanQueue { public String toString () { if (size == 0) { return "[]"; } final boolean[] values = this.values; final int head = this.head; final int tail = this.tail; StringBuilder sb = new StringBuilder(64); sb.append('['); sb.append(values[head]); for (int i = (head + 1) % values.length; i != tail; i = (i + 1) % values.length) { sb.append(", ").append(values[i]); } sb.append(']'); return sb.toString(); } BooleanQueue(); BooleanQueue(int initialSize); void addLast(boolean object); void addFirst(boolean object); void ensureCapacity(int additional); boolean removeFirst(); boolean removeLast(); int indexOf(boolean value); boolean removeValue(boolean value); boolean removeIndex(int index); boolean notEmpty(); boolean isEmpty(); boolean first(); boolean last(); boolean get(int index); void clear(); Iterator<Boolean> iterator(); String toString(); String toString(String separator); int hashCode(); boolean equals(Object o); public int size; }### Answer: @Test public void toStringTest () { BooleanQueue q = new BooleanQueue(1); assertEquals("[]", q.toString()); q.addLast(true); assertEquals("[true]", q.toString()); q.addLast(false); q.addLast(false); q.addLast(true); assertEquals("[true, false, false, true]", q.toString()); }
### Question: ByteMap implements Iterable<ByteMap.Entry<V>> { public V get (byte key) { return get(key, null); } ByteMap(); ByteMap(int initialCapacity); ByteMap(int initialCapacity, float loadFactor); ByteMap(ByteMap<? extends V> map); V put(byte key, V value); void putAll(ByteMap<V> map); V get(byte key); V get(byte key, V defaultValue); V remove(byte key); void shrink(int maximumCapacity); void clear(int maximumCapacity); void clear(); boolean containsValue(Object value, boolean identity); boolean containsKey(byte key); byte findKey(Object value, boolean identity, byte notFound); void ensureCapacity(int additionalCapacity); int hashCode(); boolean equals(Object obj); String toString(); Iterator<Entry<V>> iterator(); Entries<V> entries(); Values<V> values(); Keys keys(); public int size; }### Answer: @Test public void testGet(){ testAdd(); Assert.assertNull(byteMap.get((byte) 100)); Assert.assertEquals("Example0", byteMap.get((byte) 0)); Assert.assertEquals("NewExample123", byteMap.get((byte) 123)); Assert.assertEquals("Example34", byteMap.get((byte) 34)); Assert.assertEquals("Example34", byteMap.get((byte) 34, "DefaultValue")); Assert.assertEquals("DefaultValue", byteMap.get((byte) 56, "DefaultValue")); Assert.assertEquals(3, byteMap.size); }