vert.x - 如果处理程序中有要模拟的对象,则对 vertx 响应处理程序进行单元测试
问题描述
示例响应处理程序:
private static void handleGetRequest(RoutingContext ctx) {
final HttpServerResponse response = ctx.response;
try {
A a = B.getSomeA();
a.handleSomething();
}
catch (Exception ex) {System.out.println(ex);}
}
我们如何通过在处理程序中模拟对象来对上述处理程序进行单元测试?
解决方案
您需要引入一个接缝,其中的实例A
提供给Handler
. 这样的接缝允许您引入 mocks/stubs/fakes 用于测试目的。
解决方案可能很简单:
class MyHandler implements Handler<RoutingContext> {
private final Supplier<A> aSupplier;
MyHandler(Supplier<A> aSupplier) { // <-- this is your test seam
this.aSupplier = aSupplier;
}
@Override
public void handle(RoutingContext ctx) {
final HttpServerResponse response = ctx.response();
try {
A a = aSupplier.get(); // <-- a mocked version can return 'A' in any state
a.handleSomething();
}
catch (Exception ex) {System.out.println(ex);}
}
}
将 out分离Handler
为自己的类型会带来额外的好处,即能够单独测试它,但这并不是绝对必要的。
推荐阅读
- python - 我正在尝试在 ubuntu 上的崇高文本中在 python 上使用 tkinter,但我不断收到错误消息
- python - 打印出列表中项目的出现
- python-3.x - 更新画布中矩形的来源以更改背景图像
- c# - 这个“No object for moniker”是什么信息?
- django - get_object() 取决于 UpdateView 中的“请求”
- ajax - Laravel 中的数据验证不起作用
- c# - 在 C# 中从 Google Drive 发送带有附件的 MailGun 电子邮件
- spring-boot - 使用 Swagger 最新版本 2.9.2 和 HATEOS 升级 Spring boot 2.2.0 后集成测试开始失败
- vue.js - Vue - 使用 vuex 进行深度复制在 vuejs 中不起作用
- flutter - appbundle 颤振应用程序的 64 位显示停止器错误