【问题标题】:Mockrunner(Java) query with Regex使用正则表达式的 Mockrunner(Java) 查询
【发布时间】:2016-02-18 09:55:36
【问题描述】:

我正在使用 Mockrunner 为我的单元测试模拟 Sql DB。以下是我的查询:-

"select * from table where userId in (" + userIds + ")"

现在我的 userIds 依赖于状态。我不需要我的测试用例依赖于列表内的排列 - userIds。所以我不需要完全匹配,而是正则表达式匹配。我已经通过以下代码启用了正则表达式匹配:-

    StatementResultSetHandler statementHandler = connection.getStatementResultSetHandler();
    usersResult = statementHandler.createResultSet("users");
    statementHandler.setUseRegularExpressions(true);
    //How to write this regex query?
    statementHandler.prepareResultSet("select * from table where userId in .*", campaignsResult); 

但如前所述,我不知道 Mockrunner 支持的正则表达式语法。

编辑:我无法将"Select * from tables" 之类的查询与"Select * from tab .*" 匹配。所以这与我在 Mockrunner 中使用正则表达式的方式有关

【问题讨论】:

  • 您确定正则表达式语法甚至可以用作IN ... 子句的一部分吗?我认为它更适合与字段匹配,例如 SELECT * FROM users WHERE email = '.*gmail\.com';?
  • 为什么不呢?查询只是一个字符串。例如,我需要一个正则表达式来表示“select * from table where whatever here group by type, date;”
  • 是的,你是对的。我看到它现在在做什么。您可能会发现一些examples here 有助于理解正则表达式语法。看起来你可能想要... where userId in \\(.*\\)
  • @aroth 感谢您的链接。但是在我的问题中用 .* 替换 * 仍然没有帮助。我在链接上阅读更多内容,看看我做错了什么:(
  • 我认为这是因为您需要在查询中转义文字 *。否则,作为正则表达式,它匹配“selectfromtable ...”。如果您想使用正则表达式并在查询中包含文字 *,则需要对文字字符进行转义。

标签: java mocking mockrunner


【解决方案1】:

有一些有用的例子available here。例如:

public void testCorrectSQL() throws Exception {
    MockResultSet result = getStatementResultSetHandler().createResultSet();
    getStatementResultSetHandler().prepareResultSet("select.*isbn,.*quantity.*", result);
    List orderList = new ArrayList();
    orderList.add("1234567890");
    orderList.add("1111111111");
    Bookstore.order(getJDBCMockObjectFactory().getMockConnection(), orderList);
    verifySQLStatementExecuted("select.*isbn,.*quantity.*\\(isbn='1234567890'.*or.*isbn='1111111111'\\)");
}

据此,我推测它使用的是标准Java regex syntax。在这种情况下,您可能想要:

prepareResultSet("select \\* from table where userId in \\(.*\\)", campaignsResult);

...或者更简洁一些(具体取决于您的测试需要多么细粒度):

prepareResultSet("select .* from table where userId in .*", campaignsResult);

启用正则表达式匹配时需要注意的主要警告是,您在查询中需要的任何文字特殊字符(例如 *() 文字)需要在您的正则表达式才能正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 2014-01-24
    • 2014-08-11
    • 2023-03-02
    • 1970-01-01
    相关资源
    最近更新 更多