I am testing using Spring Boot with JavaFX (Based on some excellent YouTube videos that explain this).
To make it work with TestFX, I need to create the context like this:
@Override
public void init() throws Exception {
SpringApplicationBuilder builder = new SpringApplicationBuilder(MyJavaFXApplication.class);
builder.headless(false); // Needed for TestFX
context = builder.run(getParameters().getRaw().stream().toArray(String[]::new));
FXMLLoader loader = new FXMLLoader(getClass().getResource("main.fxml"));
loader.setControllerFactory(context::getBean);
rootNode = loader.load();
}
I now want to test this JavaFX application, for this I use:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class MyJavaFXApplicationUITest extends TestFXBase {
@MockBean
private MachineService machineService;
@Test
public void test() throws InterruptedException {
WaitForAsyncUtils.waitForFxEvents();
verifyThat("#statusText", (Text text ) -> text.getText().equals("Machine stopped"));
clickOn("#startMachineButton");
verifyThat("#startMachineButton", Node::isDisabled);
verifyThat("#statusText", (Text text ) -> text.getText().equals("Machine started"));
}
}
This starts a Spring context and replaces the "normal" beans with the mock beans as expected.
However, I now get a java.awt.HeadlessException
because this 'headless' property is not set to false like is done during normal startup. How to I set this property during the test?
EDIT:
Looking closer it seems that there are 2 context started, one that the Spring testing framework starts and the one I create manually in the init
method, so the application under test is not using the mocked beans. If somebody would have a clue how to get the test context reference in the init()
method, I would be very happy.