name: gpui-test description: 编写GPUI应用程序的测试。用于测试组件、异步操作或UI行为。
概述
GPUI提供了一个全面的测试框架,允许您测试UI组件、异步操作和分布式系统。测试运行在单线程执行器上,提供确定性执行和测试复杂异步场景的能力。GPUI测试使用#[gpui::test]属性,并与TestAppContext用于基本测试,VisualTestContext用于依赖窗口的测试。
规则
- 如果测试不需要窗口或渲染,我们可以避免使用
[gpui::test]和TestAppContext,只需编写简单的Rust测试。
核心测试基础设施
测试属性
基本测试
#[gpui::test]
fn my_test(cx: &mut TestAppContext) {
// 测试实现
}
异步测试
#[gpui::test]
async fn my_async_test(cx: &mut TestAppContext) {
// 异步测试实现
}
带迭代的属性测试
#[gpui::test(iterations = 10)]
fn my_property_test(cx: &mut TestAppContext, mut rng: StdRng) {
// 使用随机数据的属性测试
}
测试上下文
TestAppContext
TestAppContext提供对GPUI核心功能的访问,无需窗口:
#[gpui::test]
fn test_entity_operations(cx: &mut TestAppContext) {
// 创建实体
let entity = cx.new(|cx| MyComponent::new(cx));
// 更新实体
entity.update(cx, |component, cx| {
component.value = 42;
cx.notify();
});
// 读取实体
let value = entity.read_with(cx, |component, _| component.value);
assert_eq!(value, 42);
}
VisualTestContext
VisualTestContext扩展TestAppContext以支持窗口:
#[gpui::test]
fn test_with_window(cx: &mut TestAppContext) {
// 创建带组件的窗口
let window = cx.update(|cx| {
cx.open_window(Default::default(), |_, cx| {
cx.new(|cx| MyComponent::new(cx))
}).unwrap()
});
// 转换为视觉上下文
let mut cx = VisualTestContext::from_window(window.into(), cx);
// 访问窗口和组件
let component = window.root(&mut cx).unwrap();
}
额外资源
- 有关详细的测试模式和示例,请参阅reference.md
- 有关最佳实践和运行测试,请参阅examples.md