Issue10.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <gtest/gtest.h>
  2. #include <ArduinoJson/JsonArray.hpp>
  3. #include <ArduinoJson/JsonObject.hpp>
  4. #include <ArduinoJson/JsonValue.hpp>
  5. #include <ArduinoJson/StaticJsonBuffer.hpp>
  6. using namespace ArduinoJson;
  7. struct Person {
  8. int id;
  9. char name[32];
  10. };
  11. class Issue10 : public testing::Test {
  12. protected:
  13. virtual void SetUp() {
  14. Person boss;
  15. boss.id = 1;
  16. strcpy(boss.name, "Jeff");
  17. Person employee;
  18. employee.id = 2;
  19. strcpy(employee.name, "John");
  20. persons[0] = boss;
  21. persons[1] = employee;
  22. }
  23. void checkJsonString(JsonContainer &p) {
  24. char buffer[256];
  25. p.printTo(buffer, sizeof(buffer));
  26. EXPECT_STREQ("[{\"id\":1,\"name\":\"Jeff\"},{\"id\":2,\"name\":\"John\"}]",
  27. buffer);
  28. }
  29. void nodeCountMustBe(int expected) { EXPECT_EQ(expected, json.size()); }
  30. Person persons[2];
  31. StaticJsonBuffer<20> json;
  32. };
  33. TEST_F(Issue10, PopulateArrayByAddingAnObject) {
  34. JsonArray array = json.createArray();
  35. for (int i = 0; i < 2; i++) {
  36. JsonObject object = json.createObject();
  37. object["id"] = persons[i].id;
  38. object["name"] = persons[i].name;
  39. array.add(object); // <- adds a reference to an existing objet (creates 2
  40. // extra proxy nodes)
  41. }
  42. checkJsonString(array);
  43. nodeCountMustBe(15);
  44. }
  45. TEST_F(Issue10, PopulateArrayByCreatingNestedObjects) {
  46. JsonArray array = json.createArray();
  47. for (int i = 0; i < 2; i++) {
  48. JsonObject object = array.createNestedObject();
  49. object["id"] = persons[i].id;
  50. object["name"] = persons[i].name;
  51. }
  52. checkJsonString(array);
  53. nodeCountMustBe(11);
  54. }