我正在使用带有 JavaFX 的 Spring Boot 进行测试(基于解释这一点的 some excellent YouTube videos)。
为了让它与 TestFX 一起工作,我需要创建这样的上下文:
@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();
}
我现在想测试这个 JavaFX 应用程序,为此我使用:
@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"));
}
}
这将启动一个 Spring 上下文,并按预期用模拟 bean 替换“普通”bean。
但是,我现在得到了一个
java.awt.HeadlessException
,因为这个“ headless ”属性没有像正常启动期间那样设置为 false。如何在测试期间设置此属性?编辑:
仔细观察,似乎有 2 个上下文已启动,一个是 Spring 测试框架启动的,另一个是我在
init
方法中手动创建的,因此被测应用程序未使用模拟 bean。如果有人知道如何在 init()
方法中获取测试上下文引用,我会很高兴。
最佳答案
@SpringBootTest 使用 SpringBootContextLoader 类作为上下文加载器,因此 ApplicationContext 是从 SpringBootContextLoader.loadContext
方法加载的,如下所示:
SpringApplication application = getSpringApplication();
......
return application.run();
当调用
application.run()
方法时,应用程序使用它的内部 headless 属性配置系统 headless 属性。所以, 如果我们想在 Spring Boot 测试中设置 'headless' 属性,只需创建一个自定义的特定 ContextLoader 类扩展 SpringBootContextLoader 类,并覆盖方法
getSpringApplication
将 headless 属性设置为 false,然后使用注释分配特定的 ContextLoader @SpringBootTest 的 @ContextConfiguration。编码:public class HeadlessSpringBootContextLoader extends SpringBootContextLoader {
@Override
protected SpringApplication getSpringApplication() {
SpringApplication application = super.getSpringApplication();
application.setHeadless(false);
return application;
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.NONE)
@ContextConfiguration(loader = HeadlessSpringBootContextLoader.class)
public class ApplicationTests {
@Test
public void contextLoads() {
}
}
关于java - 如何在 Spring Boot 测试中设置 'headless' 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39265486/