Merge JavaFX JUnit fixtures and deterministic docking activation test

This commit is contained in:
2026-11-23 19:29:33 +01:00
9 changed files with 324 additions and 90 deletions
+6
View File
@@ -54,6 +54,12 @@ Optional mapped JDBC DataGrid source, initially qualified with H2. See [data-gri
JavaFX docking, saved HTML/SingleFile viewing, standalone bars and optional MVVM bindings from FXML views to ordinary Java models. Docking works with plain JavaFX and standard FXMLLoader without initializing MVVM. See [fx/README.md](fx/README.md) and the [docking guide](fx/docs/docking.md). JavaFX docking, saved HTML/SingleFile viewing, standalone bars and optional MVVM bindings from FXML views to ordinary Java models. Docking works with plain JavaFX and standard FXMLLoader without initializing MVVM. See [fx/README.md](fx/README.md) and the [docking guide](fx/docs/docking.md).
### fx-test
JavaFX fixtures for JUnit Jupiter. Add `de.neitzel.lib:fx-test` at the same version as `fx` with Maven scope `test`. Annotate the class with `@FxTest` and accept an `FxFixture` parameter in each test. Use `fx.run` for actions, `fx.call` for values and `fx.await("dialog closed", () -> !dialog.isShowing())` to wait from the test thread. `fx.load(fxml, model, services)` uses the production ViewLoader and a fresh ViewModelContext per test.
The extension keeps JavaFX running between tests, isolates the class with JUnit's `@Isolated`, hides windows opened by each test, closes its view context and reports unhandled FX callbacks at teardown. Complete background work before the test ends. Select the backend in the test JVM before toolkit startup, for example `-Dglass.platform=Headless`.
### injection ### injection
Package scanner and type-based container used by `fx`. See [injection/README.md](injection/README.md). Package scanner and type-based container used by `fx`. See [injection/README.md](injection/README.md).
+37
View File
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.6-SNAPSHOT</version>
</parent>
<artifactId>fx-test</artifactId>
<dependencies>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<glass.platform>Headless</glass.platform>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,37 @@
package de.neitzel.fx.test;
import java.lang.reflect.Method;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolver;
final class FxExtension implements BeforeEachCallback, AfterEachCallback, ParameterResolver {
private static final ExtensionContext.Namespace NAMESPACE = ExtensionContext.Namespace.create(FxExtension.class);
@Override
public void beforeEach(ExtensionContext context) throws Exception {
var fixture = new FxFixture();
fixture.start();
context.getStore(NAMESPACE).put(FxFixture.class, fixture);
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
var fixture = context.getStore(NAMESPACE).remove(FxFixture.class, FxFixture.class);
if (fixture != null) fixture.finish();
}
@Override
public boolean supportsParameter(ParameterContext parameter, ExtensionContext context) {
return parameter.getParameter().getType() == FxFixture.class
&& parameter.getDeclaringExecutable() instanceof Method
&& context.getStore(NAMESPACE).get(FxFixture.class) != null;
}
@Override
public Object resolveParameter(ParameterContext parameter, ExtensionContext context) {
return context.getStore(NAMESPACE).get(FxFixture.class, FxFixture.class);
}
}
@@ -0,0 +1,140 @@
package de.neitzel.fx.test;
import de.neitzel.fx.view.LoadedView;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import de.neitzel.injection.ApplicationContext;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BooleanSupplier;
import javafx.application.Platform;
import javafx.stage.Window;
/** JavaFX test operations scoped to one JUnit test. Obtain the fixture through {@link FxTest}. */
public final class FxFixture {
private static final long TIMEOUT_SECONDS = 10;
private final ViewModelContext models = new ViewModelContext();
private final List<Throwable> callbackFailures = new ArrayList<>();
private List<Window> previousWindows;
private Thread.UncaughtExceptionHandler previousHandler;
/** An FX-thread action that may propagate a checked exception. */
@FunctionalInterface
public interface Action {
/**
* Performs the action.
* @throws Exception on failure
*/
void run() throws Exception;
}
FxFixture() {}
void start() throws Exception {
try {
Platform.startup(() -> {});
} catch (IllegalStateException alreadyStarted) {
// A previous test or another JavaFX client has started this JVM's toolkit.
}
run(() -> {
Platform.setImplicitExit(false);
previousWindows = List.copyOf(Window.getWindows());
previousHandler = Thread.currentThread().getUncaughtExceptionHandler();
Thread.currentThread().setUncaughtExceptionHandler((thread, error) -> callbackFailures.add(error));
});
}
/**
* Runs an action on the FX thread and propagates its failure to the test.
* @param action test action
* @throws Exception if the action fails or the wait is interrupted or times out
*/
public void run(Action action) throws Exception {
call(() -> {
action.run();
return null;
});
}
/**
* Returns the result of an FX-thread operation, with a bounded wait on the calling thread.
* @param <T> result type
* @param action operation to perform
* @return the value returned by the operation
* @throws Exception if the operation fails or the wait is interrupted or times out
*/
public <T> T call(Callable<T> action) throws Exception {
if (Platform.isFxApplicationThread()) return action.call();
var task = new FutureTask<>(action);
Platform.runLater(task);
try {
return task.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (ExecutionException failure) {
if (failure.getCause() instanceof Exception exception) throw exception;
if (failure.getCause() instanceof Error error) throw error;
throw new AssertionError(failure.getCause());
} catch (TimeoutException | InterruptedException failure) {
task.cancel(false);
throw failure;
}
}
/**
* Waits on the test thread while evaluating the named condition on the FX thread.
* @param description expected state, included in the timeout message
* @param condition UI predicate to evaluate
* @throws Exception if evaluation fails or waiting is interrupted
* @throws AssertionError if the condition stays false
*/
public void await(String description, BooleanSupplier condition) throws Exception {
if (Platform.isFxApplicationThread()) throw new IllegalStateException("await requires the test thread");
long start = System.nanoTime();
while (!call(condition::getAsBoolean)) {
if (System.nanoTime() - start >= TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS)) {
throw new AssertionError("Timed out waiting for " + description);
}
Thread.sleep(15);
}
}
/**
* Loads production FXML on the FX thread in the test's automatically closed model context.
* @param fxml view resource
* @param model model for the view
* @param services controller and service container
* @return managed view
* @throws Exception if the view cannot be loaded or the wait is interrupted or times out
*/
public LoadedView load(URL fxml, Object model, ApplicationContext services) throws Exception {
return call(() -> ViewLoader.load(fxml, model, services, models));
}
void finish() throws Exception {
run(() -> {
try {
for (var window : List.copyOf(Window.getWindows()).reversed()) {
if (!previousWindows.contains(window)) window.hide();
}
} finally {
try {
models.close();
} finally {
Thread.currentThread().setUncaughtExceptionHandler(previousHandler);
}
}
if (!callbackFailures.isEmpty()) {
var failure = new AssertionError("Unhandled exception on the JavaFX application thread",
callbackFailures.getFirst());
callbackFailures.stream().skip(1).forEach(failure::addSuppressed);
throw failure;
}
});
}
}
@@ -0,0 +1,20 @@
package de.neitzel.fx.test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.api.parallel.Isolated;
/** Runs a JavaFX test class in isolation and supplies an FxFixture to each test method. */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Isolated
@Execution(ExecutionMode.SAME_THREAD)
@ExtendWith(FxExtension.class)
public @interface FxTest {}
@@ -0,0 +1,57 @@
package de.neitzel.fx.test;
import de.neitzel.injection.ApplicationContext;
import java.io.IOException;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import lombok.Getter;
import lombok.Setter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
@FxTest
public class FxFixtureTest {
@Getter @Setter
public static class Person {
private String name = "Ada";
}
@Test
void teardownDetachesLoadedViewsAndReportsUnhandledCallbacks(FxFixture fx) throws Exception {
var person = new Person();
var nested = new FxFixture();
var problem = new IllegalStateException("callback failed");
nested.start();
var view = nested.load(getClass().getResource("name.fxml"), person, new ApplicationContext(Person.class));
var field = nested.call(() -> (TextField) view.getRoot());
var stage = nested.call(() -> {
assertEquals("Ada", field.getText());
field.setText("Lin");
assertEquals("Lin", person.getName());
var window = new Stage();
window.setScene(new Scene(field));
window.show();
return window;
});
nested.run(() -> Platform.runLater(() -> { throw problem; }));
assertSame(problem, assertThrows(AssertionError.class, nested::finish).getCause());
fx.run(() -> {
assertFalse(stage.isShowing());
field.setText("Detached");
assertEquals("Lin", person.getName());
});
}
@Test
void nestedCallsPropagateTheOriginalFailureAndCannotBlockTheFxThread(FxFixture fx) throws Exception {
var problem = new IOException("failed");
assertSame(problem, assertThrows(IOException.class, () -> fx.run(() -> {
assertTrue(fx.call(Platform::isFxApplicationThread));
assertThrows(IllegalStateException.class, () -> fx.await("next pulse", () -> false));
throw problem;
})));
}
}
@@ -0,0 +1,8 @@
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.TextField?>
<TextField xmlns:fx="http://javafx.com/fxml/1" fx:id="field">
<fx:define><BindingList>
<DirectBinding control="field" property="text" path="name" direction="both"/>
</BindingList></fx:define>
</TextField>
@@ -9,125 +9,53 @@ import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId; import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager; import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions; import de.neitzel.fx.docking.DockingOptions;
import javafx.animation.AnimationTimer;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Bounds;
import javafx.scene.Scene; import javafx.scene.Scene;
import javafx.scene.control.TextArea; import javafx.scene.control.TextArea;
import javafx.scene.input.MouseButton;
import javafx.scene.robot.Robot;
import javafx.stage.Stage; import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/** Activating a background window is an applied action even when its selected tab stays the same. */ /** Activating a background window is an applied action even when its selected tab stays the same. */
class ActivateDockingWindowTest { class ActivateDockingWindowTest {
@BeforeAll @BeforeAll
static void startJavaFx() throws Exception { static void startJavaFx() throws Exception {
FxThread.start(); FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
} }
@Test @Test
void activatingTheSameContentInABackgroundWindowReportsApplied() throws Exception { void activatingTheSameContentInABackgroundWindowReportsApplied() throws Exception {
AtomicReference<Fixture> state = new AtomicReference<>();
FxThread.onFx(() -> { FxThread.onFx(() -> {
DockLayout initial = new DockLayout(); DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors")); initial.setCenter(new DockGroupDefinition("editors"));
DockPane pane = new DockPane(); DockPane pane = new DockPane();
pane.setInitialLayout(initial); pane.setInitialLayout(initial);
Stage main = new Stage(); Stage main = spy(new Stage());
main.setScene(new Scene(pane, 480, 280)); main.setScene(new Scene(pane, 480, 280));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions()); DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea editor = new TextArea("Unsaved text"); TextArea editor = new TextArea("Unsaved text");
Dockable dockable = new Dockable(new DockableId("notes"), editor); Dockable dockable = new Dockable(new DockableId("notes"), editor);
manager.open(dockable, DockTarget.area("editors")); manager.open(dockable, DockTarget.area("editors"));
Stage other = new Stage();
other.setScene(new Scene(new TextArea("Other window"), 240, 160)); // Only the desktop's window state is simulated. Selection, scene focus and
state.set(new Fixture(main, other, manager, dockable)); // the activation result all come from the real controls and manager.
main.show(); doReturn(true).when(main).isShowing();
doReturn(true).when(main).isFocused();
manager.activate(dockable.getId()); manager.activate(dockable.getId());
assertSame(dockable, manager.activeDockable());
assertSame(editor, main.getScene().getFocusOwner());
assertInstanceOf(ActionResult.NoChange.class, manager.activate(dockable.getId()));
doReturn(false).when(main).isFocused();
clearInvocations(main);
assertInstanceOf(ActionResult.Applied.class, manager.activate(dockable.getId()));
verify(main).requestFocus();
}); });
Fixture fixture = state.get();
try {
focus(fixture.main());
FxThread.onFx(() -> fixture.other().show());
focus(fixture.other());
FxThread.onFx(() -> {
assertFalse(fixture.main().isFocused());
assertSame(fixture.dockable(), fixture.manager().activeDockable());
assertSame(fixture.dockable().getContent(), fixture.main().getScene().getFocusOwner());
assertInstanceOf(ActionResult.Applied.class, fixture.manager().activate(fixture.dockable().getId()));
});
} finally {
FxThread.onFx(() -> {
fixture.other().hide();
fixture.main().hide();
});
}
} }
private static void focus(Stage stage) throws Exception {
CountDownLatch focused = new CountDownLatch(1);
ChangeListener<Boolean> listener = (observable, old, current) -> {
if (current) focused.countDown();
};
AnimationTimer clickAfterDisplay = new AnimationTimer() {
private int pulses;
private long lastClick;
@Override
public void handle(long now) {
if (stage.isFocused()) {
focused.countDown();
stop();
return;
}
if (++pulses < 2) return;
if (now - lastClick < 250_000_000) return;
lastClick = now;
Bounds bounds = stage.getScene().getRoot().localToScreen(
stage.getScene().getRoot().getBoundsInLocal());
Robot robot = new Robot();
robot.mouseMove(bounds.getCenterX(), bounds.getCenterY());
robot.mouseClick(MouseButton.PRIMARY);
if (stage.isFocused()) focused.countDown();
}
};
FxThread.onFx(() -> {
stage.focusedProperty().addListener(listener);
stage.setAlwaysOnTop(true);
stage.toFront();
stage.requestFocus();
stage.getScene().getRoot().applyCss();
stage.getScene().getRoot().layout();
clickAfterDisplay.start();
});
try {
// A native click activates the application even if the previous test or
// another application owned desktop focus. RequestFocus alone cannot
// establish that precondition reliably on macOS. FX pulses do not
// guarantee that the native compositor has displayed the window;
// retry only this focus precondition within the bounded wait.
assertTrue(focused.await(5, TimeUnit.SECONDS), "Desktop did not focus the requested window");
} finally {
FxThread.onFx(() -> {
clickAfterDisplay.stop();
stage.focusedProperty().removeListener(listener);
stage.setAlwaysOnTop(false);
});
}
}
private record Fixture(Stage main, Stage other, DockingManager manager, Dockable dockable) { }
} }
+1
View File
@@ -24,6 +24,7 @@
<module>data-grid</module> <module>data-grid</module>
<module>data-grid-jdbc</module> <module>data-grid-jdbc</module>
<module>fx</module> <module>fx</module>
<module>fx-test</module>
<module>fx-example</module> <module>fx-example</module>
<module>gson</module> <module>gson</module>
<module>net</module> <module>net</module>