В настоящее время у меня есть тестовая структура (Java/Cucumber/Testng/RestAssud), и я хочу выполнить свой запрос SQL только один раз, используя Java.Sql.Statement. Прямо сейчас он выполняет вызов БД каждый раз, когда я пытаюсь добавлять один столбец DB и значения в список, чтобы подтвердить этот список в отношении узла ответа JSON (Пример - утверждение itemlist значения совпадает с json content.item значения (которые, вероятно, также должны быть добавлены в списке для лучшей эффективности). , и он снова запустит один и тот же запрос. > Query (db2): < /p>
SELECT ITM_NBR AS ITEM, ADD_DT AS ADD_DATE, UPD_DM AS UPDATE_DATE FROM SCHEMA.DMD_ITEM WHERE ITM_NBR = itemNbr AND add_dt >= (current_date - nbrDays DAYS) ORDER BY UPDATE_DATE LIMIT 100 WITH UR
< /code>
public static List getDataFromDb(String query, int index) throws SQLException {
List expData = new ArrayList();
ResultSet res = null;
Statement stmt = db2Connection.createStatement();
try {
if (query == null) {
Reporter.log("Expected behaviuor, Query is empty only in cases of negative cases", true);
} else {
res = stmt.executeQuery(query);
while (res.next()) {
expData.add(res.getObject(index));
}
}
} catch (SQLException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
} finally {
if (!(res.isClosed() && !stmt.isClosed())) {
try {
Reporter.log("Closing Result set", true);
res.close();
stmt.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
return expData;
}
< /code>
Test logic:
@Then("Check for the DB values matching the response values for item {string},{string},{string}")
public void checkRespAgainstDB(String item, String duration, String queryKey) throws SQLException {
String query = testDBProps.getProperty(queryKey);
String queryWithInputs = query.replace("itemNbr", item).replace("nbrDays", duration);
List itemList = new ArrayList();
itemList = DatabaseConfig.getDataFromDb(queryWithInputs, 1);
String resp = gResponse.asString();
System.out.println("query name is + " + queryKey + " and queryKey value is " + queryWithInputs);
System.out.println("Response is:" + "\n" + "\n" + resp);
try {
if (itemList.size() == 0) {
Assert.fail();
} else {
JsonPath json = new JsonPath(resp);
for (int i = 0; i < itemList.size(); i++) {
int numOfElements = json.getInt("numberOfElements");
if (itemList.size() != numOfElements) {
Assert.fail("Item List count is " + itemList.size() + " and json numberOfElements is " + numOfElements);
}
System.out.println("Checking for item list");
if (!itemList.isEmpty()) {
GenericUtils.compareDBvaluesAndResponse(itemList, "content.item", json, i);
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
< /code>
compare DB to response:
public static void compareDBvaluesAndResponse(List objList, String responseNode, JsonPath json,
int index) {
List actualStringResponse = new ArrayList();
actualStringResponse = json.get(responseNode);
if (actualStringResponse == null) {
Reporter.log("The response is empty", true);
Assert.fail();
} else {
AsserEquals_Object(actualStringResponse.get(index).toString(),
objList.get(index).toString().trim(), "Actual and Expected are the same");
}
}
public static void AsserEquals_Object(Object actual, Object expected, String phase) {
try {
Assert.assertEquals(actual, expected);
Reporter.log("INFO:" + phase + " (Successful- Expected: " + expected + " | Actual: " + actual, true);
} catch (Exception e) {
Reporter.log("ERROR:" + phase + " (Failed - Expected:" + expected + " and Actual:" + actual, true);
Assert.fail();
throw e;
}
}
< /code>
Is there a way to do this without calling the db multiple times with the same query? Please let me know for any ideas.
Подробнее здесь: https://stackoverflow.com/questions/794 ... n-value-ag