【问题标题】:Unit test vertx response handlers if there are objects within the handler to mock如果处理程序中有要模拟的对象,则对 vertx 响应处理程序进行单元测试
【发布时间】:2020-07-22 13:28:00
【问题描述】:
示例响应处理程序:
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);}
}
我们如何通过在处理程序中模拟对象来对上述处理程序进行单元测试?
【问题讨论】:
标签:
vert.x
vertx-verticle
vertx-httpclient
【解决方案1】:
您需要引入一个接缝,将A 的实例提供给Handler。这样的接缝允许您引入模拟/存根/假货以进行测试。
解决方案可能很简单:
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);}
}
}
将Handler 分离为自己的类型会带来额外的好处,即能够单独对其进行测试,但这并不是绝对必要的。