Skip to content

Commit

Permalink
Use lambdas and method references in :robolectric
Browse files Browse the repository at this point in the history
This commit replaces anonymous class creation with method references and lambdas.
  • Loading branch information
MGaetan89 committed Jan 18, 2025
1 parent 101aba5 commit 8a1f3d2
Show file tree
Hide file tree
Showing 32 changed files with 143 additions and 415 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicBoolean;
Expand Down Expand Up @@ -272,13 +271,9 @@ private void postDispatchActivityResult(
ShadowActivity shadowActivity, String target, int requestCode, ActivityResult ar) {
new Handler(Looper.getMainLooper())
.post(
new Runnable() {
@Override
public void run() {
() ->
shadowActivity.internalCallDispatchActivityResult(
target, requestCode, ar.getResultCode(), ar.getResultData());
}
});
target, requestCode, ar.getResultCode(), ar.getResultData()));
}

private ActivityResult stubResultFor(Intent intent) {
Expand All @@ -287,13 +282,8 @@ private ActivityResult stubResultFor(Intent intent) {
}

FutureTask<ActivityResult> task =
new FutureTask<ActivityResult>(
new Callable<ActivityResult>() {
@Override
public ActivityResult call() throws Exception {
return IntentStubberRegistry.getInstance().getActivityResultForIntent(intent);
}
});
new FutureTask<>(
() -> IntentStubberRegistry.getInstance().getActivityResultForIntent(intent));
ShadowInstrumentation.runOnMainSyncNoIdle(task);

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,11 @@ public void evaluate() throws Throwable {
// application loading in the future
RuntimeEnvironment.getApplication();
BackgroundExecutor.runInBackground(
new Runnable() {
@Override
public void run() {
try {
base.evaluate();
} catch (Throwable t) {
throwable.set(t);
}
() -> {
try {
base.evaluate();
} catch (Throwable t) {
throwable.set(t);
}
});
if (throwable.get() != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,11 @@ public void isMainThread_forNewThread_withoutSwitch() throws InterruptedExceptio
final AtomicBoolean res = new AtomicBoolean();
final CountDownLatch finished = new CountDownLatch(1);
Thread t =
new Thread() {
@Override
public void run() {
res.set(RuntimeEnvironment.isMainThread());
finished.countDown();
}
};
new Thread(
() -> {
res.set(RuntimeEnvironment.isMainThread());
finished.countDown();
});
RuntimeEnvironment.setMainThread(Thread.currentThread());
t.start();
if (!finished.await(1000, MILLISECONDS)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,9 @@ public void click_shouldCallPreferenceClickListener() {

boolean[] holder = new boolean[1];
preference.setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
holder[0] = true;
return true;
}
clickedPreference -> {
holder[0] = true;
return true;
});

shadowOf(preference).click();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -364,8 +364,7 @@ public void testResetterFails_reportsFailureAndContinues() {
new StubSdk(RuntimeEnvironment.getApiLevel(), true),
shadowProviders,
telpArray);
RuntimeException e =
assertThrows(RuntimeException.class, () -> androidTestEnvironment.resetState());
RuntimeException e = assertThrows(RuntimeException.class, androidTestEnvironment::resetState);
assertThat(e).hasMessageThat().contains("Reset failed");
assertThat(workingShadowProvider.wasReset).isTrue();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,9 @@ public void setUp() throws Exception {
public void executionRunsInBackgroundThread() {
final Thread testThread = Thread.currentThread();
executorService.execute(
new Runnable() {
@Override
public void run() {
assertThat(Thread.currentThread()).isNotSameInstanceAs(testThread);
executedTasksRecord.add("task ran");
}
() -> {
assertThat(Thread.currentThread()).isNotSameInstanceAs(testThread);
executedTasksRecord.add("task ran");
});
assertThat(executedTasksRecord).containsExactly("task ran");
}
Expand Down Expand Up @@ -84,12 +81,8 @@ public void whenAwaitingTerminationAfterShutdown_TrueIsReturned() throws Interru
@Test
public void exceptionsPropagated() {
Callable<Void> throwingCallable =
new Callable<Void>() {

@Override
public Void call() throws Exception {
throw new IllegalStateException("I failed");
}
() -> {
throw new IllegalStateException("I failed");
};
try {
executorService.submit(throwingCallable);
Expand All @@ -102,13 +95,10 @@ public Void call() throws Exception {
@Test
public void postingTasks() {
Runnable postingRunnable =
new Runnable() {
@Override
public void run() {
executedTasksRecord.add("first");
executorService.execute(() -> executedTasksRecord.add("third"));
executedTasksRecord.add("second");
}
() -> {
executedTasksRecord.add("first");
executorService.execute(() -> executedTasksRecord.add("third"));
executedTasksRecord.add("second");
};
executorService.execute(postingRunnable);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,13 +177,10 @@ public void exceptionsPropagated() {
@Test
public void postingTasks() {
Runnable postingRunnable =
new Runnable() {
@Override
public void run() {
executedTasksRecord.add("first");
executorService.execute(() -> executedTasksRecord.add("third"));
executedTasksRecord.add("second");
}
() -> {
executedTasksRecord.add("first");
executorService.execute(() -> executedTasksRecord.add("third"));
executedTasksRecord.add("second");
};
executorService.execute(postingRunnable);
executorService.runAll();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public void settingAllLciSubelementFieldsWithNoZaxisFields() {

assertThat(responderLocation.isLciSubelementValid()).isTrue();
assertThat(responderLocation.isZaxisSubelementValid()).isFalse();
assertThrows(IllegalStateException.class, () -> responderLocation.getFloorNumber());
assertThrows(IllegalStateException.class, responderLocation::getFloorNumber);
}

@Test
Expand All @@ -62,8 +62,8 @@ public void settingPartsOfLciSubelementFields() {

assertThat(responderLocation.isLciSubelementValid()).isFalse();
assertThat(responderLocation.isZaxisSubelementValid()).isFalse();
assertThrows(IllegalStateException.class, () -> responderLocation.getAltitude());
assertThrows(IllegalStateException.class, () -> responderLocation.getFloorNumber());
assertThrows(IllegalStateException.class, responderLocation::getAltitude);
assertThrows(IllegalStateException.class, responderLocation::getFloorNumber);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -880,18 +880,17 @@ public void shouldBeAbleToBeUsedFromDifferentThread() {
final CountDownLatch sync = new CountDownLatch(1);
final Throwable[] error = {null};

new Thread() {
@Override
public void run() {
try (Cursor c = executeQuery("select * from table_name")) {
} catch (Throwable e) {
e.printStackTrace();
error[0] = e;
} finally {
sync.countDown();
}
}
}.start();
new Thread(
() -> {
try (Cursor c = executeQuery("select * from table_name")) {
} catch (Throwable e) {
e.printStackTrace();
error[0] = e;
} finally {
sync.countDown();
}
})
.start();

try {
sync.await();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ public void removeAccessibilityStateChangeListener_returnsFalseIfNotRegistered()
@Test
public void setTouchExplorationEnabled_invokesCallbacks() {
AtomicBoolean enabled = new AtomicBoolean(false);
accessibilityManager.addTouchExplorationStateChangeListener(val -> enabled.set(val));
accessibilityManager.addTouchExplorationStateChangeListener(enabled::set);
shadowOf(accessibilityManager).setTouchExplorationEnabled(true);
assertThat(enabled.get()).isTrue();
shadowOf(accessibilityManager).setTouchExplorationEnabled(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1650,9 +1650,9 @@ public void callOnGetDirectActions_malformedDirectAction_fails() {
testActivity.setReturnMalformedDirectAction(true);
assertThrows(
NullPointerException.class,
() -> {
shadowOf(testActivity).callOnGetDirectActions(new CancellationSignal(), (unused) -> {});
});
() ->
shadowOf(testActivity)
.callOnGetDirectActions(new CancellationSignal(), (unused) -> {}));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ public void testLinkToDeath_twice() {
@Test
public void testLinkToDeath_weakReference() {
Binder binder = new Binder();
//noinspection Convert2Lambda
binder.linkToDeath(
new DeathRecipient() {
@Override
Expand Down Expand Up @@ -175,7 +176,7 @@ public void testGetCallingUidOrThrowWithValueSet() {
public void testGetCallingUidOrThrowWithValueNotSet() {
ShadowBinder.reset();
IllegalStateException ex =
assertThrows(IllegalStateException.class, () -> Binder.getCallingUidOrThrow());
assertThrows(IllegalStateException.class, Binder::getCallingUidOrThrow);

// Typo in "transaction" is intentional to match platform
assertThat(ex).hasMessageThat().isEqualTo("Thread is not in a binder transcation");
Expand All @@ -201,7 +202,7 @@ public void testResetUpdatesGetCallingUidOrThrow() {
ShadowBinder.setCallingUid(123);
ShadowBinder.reset();

assertThrows(IllegalStateException.class, () -> Binder.getCallingUidOrThrow());
assertThrows(IllegalStateException.class, Binder::getCallingUidOrThrow);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -900,6 +900,7 @@ private PendingIntent createTestPendingIntent(Intent intent) {
}

private BluetoothAdapter.LeScanCallback newLeScanCallback() {
//noinspection Convert2Lambda
return new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,13 @@ public void startBugreport_noPermission() {

assertThrows(
SecurityException.class,
() -> {
shadowBugreportManager.startBugreport(
createWriteFile("bugreport"),
createWriteFile("screenshot"),
new BugreportParams(BugreportParams.BUGREPORT_MODE_FULL),
directExecutor(),
callback);
});
() ->
shadowBugreportManager.startBugreport(
createWriteFile("bugreport"),
createWriteFile("screenshot"),
new BugreportParams(BugreportParams.BUGREPORT_MODE_FULL),
directExecutor(),
callback));
shadowMainLooper().idle();

assertThat(shadowBugreportManager.isBugreportInProgress()).isFalse();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,7 @@ public void isDefaultNetworkActive_notActive() {
}

private static ConnectivityManager.OnNetworkActiveListener createSimpleOnNetworkActiveListener() {
//noinspection Convert2Lambda
return new ConnectivityManager.OnNetworkActiveListener() {
@Override
public void onNetworkActive() {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,20 +52,12 @@ public void getProperty_empty() {

@Test
public void getProperty_nullNamespace() {
assertThrows(
NullPointerException.class,
() -> {
DeviceConfig.getProperty(null, KEY);
});
assertThrows(NullPointerException.class, () -> DeviceConfig.getProperty(null, KEY));
}

@Test
public void getProperty_nullName() {
assertThrows(
NullPointerException.class,
() -> {
DeviceConfig.getProperty(NAMESPACE, null);
});
assertThrows(NullPointerException.class, () -> DeviceConfig.getProperty(NAMESPACE, null));
}

@Test
Expand Down Expand Up @@ -104,10 +96,7 @@ public void getString_nullNamespace() {
@Test
public void getString_nullName() {
assertThrows(
NullPointerException.class,
() -> {
DeviceConfig.getString(NAMESPACE, null, "defaultValue");
});
NullPointerException.class, () -> DeviceConfig.getString(NAMESPACE, null, "defaultValue"));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,10 @@ public void sendAppPrivateCommandListenerIsNotified() {
Bundle expectedBundle = new Bundle();

ShadowInputMethodManager.PrivateCommandListener listener =
new ShadowInputMethodManager.PrivateCommandListener() {
@Override
public void onPrivateCommand(View view, String action, Bundle data) {
assertThat(view).isEqualTo(expectedView);
assertThat(action).isEqualTo(expectedAction);
assertThat(data).isEqualTo(expectedBundle);
}
(view, action, data) -> {
assertThat(view).isEqualTo(expectedView);
assertThat(action).isEqualTo(expectedAction);
assertThat(data).isEqualTo(expectedBundle);
};

shadow.setAppPrivateCommandListener(listener);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public void exceptionOnMainThreadPropagated() {
() -> {
throw new RuntimeException("Exception should be propagated!");
});
assertThrows(RuntimeException.class, () -> shadowMainLooper.idle());
assertThrows(RuntimeException.class, shadowMainLooper::idle);

// Restore main looper and main thread to avoid error at tear down
ShadowPausedLooper.resetLoopers();
Expand Down Expand Up @@ -129,10 +129,7 @@ public void mainThreadDies_resetRestartsLooper() {
}
Preconditions.checkNotNull(exception);
ShadowPausedLooper.resetLoopers();
handler.post(
() -> {
didRun.set(true);
});
handler.post(() -> didRun.set(true));
shadowLooper.idle();

assertThat(didRun.get()).isTrue();
Expand Down
Loading

0 comments on commit 8a1f3d2

Please sign in to comment.