测试 26.03
TestBed 会在普通的 JUnit 测试中运行视图,无需浏览器。在 Spring Boot 应用中,视图从 Spring 获取其 bean,路由也受 Spring Security 保护,因此测试还需要 Spring 上下文。测试类使用 @SpringBootTest 加载上下文,并使用 @WebforjTest 加载视图;两者可以协同工作,无需其他设置。
本页介绍 Spring 带来的功能。无论是否使用 Spring,查找组件、与组件交互、断言和快照的用法都相同,详见 TestBed 文档。
添加依赖
将 webforj-spring-testbed 添加为测试范围依赖。webforJ 物料清单会管理其版本,该模块还会引入 JUnit TestBed:
<dependency>
<groupId>com.webforj</groupId>
<artifactId>webforj-spring-testbed</artifactId>
<scope>test</scope>
</dependency>
使用 webforj-spring 风格生成的项目已经导入了物料清单和提供 JUnit 的 spring-boot-starter-test。
使用 Spring bean 的视图
下面的视图通过构造函数接收一个服务,并向用户输入的姓名问好:
import com.webforj.component.Composite;
import com.webforj.component.field.TextField;
import com.webforj.component.html.elements.Div;
import com.webforj.component.html.elements.Paragraph;
import com.webforj.router.annotation.Route;
import com.webforj.router.security.annotation.AnonymousAccess;
import com.webforj.samples.spring.GreetingService;
@Route("/")
@AnonymousAccess
public class WelcomeView extends Composite<Div> {
public WelcomeView(GreetingService greetings) {
TextField name = new TextField("Name");
Paragraph greeting = new Paragraph();
name.onModify(e -> greeting.setText(greetings.greet(name.getValue())));
getBoundComponent().add(name, greeting);
}
}
import org.springframework.stereotype.Service;
@Service
public class GreetingService {
public String greet(String name) {
return "Welcome, " + name + "!";
}
}
测试同时使用这两个注解。@SpringBootTest 会从 @SpringBootApplication 类加载应用上下文,和其他 Spring Boot 测试一样;@WebforjTest 则会注册视图。测试通过 @Autowired 获取同一个服务 bean,因此可以将视图显示的内容与服务返回的内容进行比较:
import static com.webforj.testbed.assertion.WebforjAssertions.verifyThat;
import com.webforj.automation.act.UserInteraction;
import com.webforj.automation.find.ComponentLocator;
import com.webforj.component.field.TextField;
import com.webforj.component.html.elements.Paragraph;
import com.webforj.samples.spring.GreetingService;
import com.webforj.testbed.WebforjTestbed;
import com.webforj.testbed.annotation.WebforjTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@WebforjTest(routeClasses = WelcomeView.class)
class WelcomeViewTest {
@Autowired
private GreetingService greetings;
@Test
void shouldGreetWithTheServiceSpringInjected(WebforjTestbed context) {
context.navigate(WelcomeView.class);
UserInteraction.type(
ComponentLocator.of(TextField.class).byLabel("Name").locate(), "Ada");
verifyThat(ComponentLocator.of(Paragraph.class).locate())
.hasText(greetings.greet("Ada"));
}
}
navigate 会通过 Spring 创建视图,因此视图获取服务的方式与应用运行时相同。视图也遵循其 bean 作用域。
每个测试都会获得独立的 WebforjTestbed,它在测试前启动、测试后结束,因此每个测试开始时页面都是空的。Spring 上下文会像其他 @SpringBootTest 一样在测试之间共享并缓存,因此单例 bean 会保留其在前一个测试中的状态。