[英]Verify the value of a key in MongoDB Java
我一直在到處尋找,但還沒有找到一種簡單而可靠的方法。
任務:我是一名 QA,我正在嘗試驗證特定密鑰是否具有 MongoDB 文檔中的預期值。 如果不是,則斷言為假。
我的問題:我的文件包含 arrays 和文件。 在 UI 中使用點表示法(例如 item.fruit.apples.type.macintosh)很容易遍歷樹。 但是在 Java 中,我能做到這一點的唯一方法是,如果我明確告訴它 item、fruit、apples、type 或 macintosh 是文檔還是數組。 例如:
{
"item": {
"fruit",
"apples"[
"type": "macintosh",
]
}
}
Document fruit = doc.getEmbedded(List.of(item, fruit), Document.class);
List<Document> apples = (List<Document>) fruit.get(apples);
for (Document apple : apples) {
actualValue = apple.getString("type");
}
if(!actualValue.equals(expectedValue)) {
Assert.fail();
}
如果開發人員決定更改或刪除任何密鑰,我的驗證將中斷。 沒有更簡單的方法可以做到這一點嗎?
在其他 stackoverflow 帖子的幫助下,我找到了解決方案:
private static Object getWithDotNotation(Document doc, String key)
throws MongoException {
String[] keys = key.split("\\.");
for (int i = 0; i < keys.length - 1; i++) {
Object o = doc.get(keys[i]);
if (o == null) {
throw new MongoException(String.format(
"Field '%s' does not exist or is not a Document", keys[i]));
}
if (o instanceof ArrayList) {
ArrayList<?> docArrayNested = (ArrayList<?>) o;
for (Object docNestedObj : docArrayNested) {
if (docNestedObj instanceof Document) {
doc = (Document) docNestedObj;
}
}
} else {
doc = (Document) o;
}
}
return doc.get(keys[keys.length - 1]);
}
這是我的 function 使用點符號迭代鍵和值:
HashMap<String, Object> map = new HashMap<>();
map.put("item.fruit.apples.type", "macintosh");
FindIterable<Document> iterable = c.find(query);
map.forEach((key, value) -> {
for (Document doc : iterable) {
Object expectedValue = map.get(key);
Object actualValue;
actualValue = getWithDotNotation(doc, key);
if (!actualValue.equals(expectedValue)) {
System.out.println("Verification Failed:: Expected value for " + key + ": " + expectedValue + ". Actual value: " + actualValue);
Assert.assertTrue(false);
} else {
System.out.println("Verification passed:: " + key + ": " + actualValue);
}
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.