0

我想模拟io.vertx.ext.jdbc.JDBCClient对以下verticle代码进行单元测试:

class A {

    private final Helper help = new Helper();

    public JsonObject checkEmailAvailability(String email, JDBCClient jdbc) throws SignUpException {
        JsonObject result = new JsonObject();
        jdbc.getConnection(conn -> help.startTx(conn.result(), beginTans -> {
            JsonArray emailParams = null;
            emailParams = new JsonArray().add(email);
            System.out.println(email);
            help.queryWithParams(conn.result(), SQL_SELECT_USER_EMAIL, emailParams, res -> {
                if (res.getNumRows() >= 1) {
                    result.put("message", "Email already registered");
                }
            });
        }));
        return result;
    }
}
4

2 回答 2

0

使用 mockito 在 vertx 中模拟 JDBCClient ..add 依赖 testCompile "io.vertx:vertx-codegen:3.2.1"

否则你会得到错误。不能模拟静态

于 2020-01-20T16:01:36.017 回答
0

你可以Mockito用来嘲笑你的jdbc行为。假设您想测试当res返回一行时 Verticle 的行为。

模拟你的jdbc

jdbc = Mockito.mock(JDBCClient.class);

然后你必须模拟一个ResultSet对象:

ResultSet res = Mockito.mock(ResultSet.class);
Mockito.when(res.getNumRows()).thenReturn(1);

然后你必须模拟AsyncResult负责返回的对象res

AsyncResult<ResultSet> asyncResultResultSet = Mockito.mock(AsyncResult.class);
Mockito.when(asyncResultResultSet.succeeded()).thenReturn(true);
Mockito.when(asyncResultResultSet.result()).thenReturn(res);

然后你必须模拟SQLConnection负责返回的对象asyncResultResultSet。用于Answer抓取处理程序并强制它返回您的模拟:

SQLConnection sqlConnection = Mockito.mock(SQLConnection.class);
Mockito.doAnswer(new Answer<AsyncResult<ResultSet>>() {
  @Override
  public AsyncResult<ResultSet> answer(InvocationOnMock arg0) throws Throwable {
    ((Handler<AsyncResult<ResultSet>>) arg0.getArgument(2)).handle(asyncResultResultSet);
    return null;
  }
}).when(sqlConnection).queryWithParams(Mockito.any(), Mockito.any(), Mockito.any());

然后你必须模拟AsyncResult负责返回的对象sqlConnection。再次,Answer帮助:

AsyncResult<SQLConnection> sqlConnectionResult = Mockito.mock(AsyncResult.class);
Mockito.when(sqlConnectionResult.succeeded()).thenReturn(true);
Mockito.when(sqlConnectionResult.result()).thenReturn(sqlConnection);
Mockito.doAnswer(new Answer<AsyncResult<SQLConnection>>() {
  @Override
  public AsyncResult<SQLConnection> answer(InvocationOnMock arg0) throws Throwable {
    ((Handler<AsyncResult<SQLConnection>>) arg0.getArgument(0)).handle(sqlConnectionResult);
    return null;
  }
}).when(jdbc).getConnection(Mockito.any());

给你。这是一堆代码,但您可以模拟多个ResultSet对象并asyncResultResultSet通过链接多个对象使用它们thenReturn

Mockito.when(asyncResultResultSet.result()).thenReturn(res1).thenReturn(res2) ...;

尽量不要测试vertx.io

如果您想查找依赖项,这是我的完整解决方案。我也使用PowermockwithVertxUnit来运行我的 Verticle。

于 2018-03-19T08:59:09.920 回答