Issue10.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "CppUnitTest.h"
  2. #include "JsonArray.h"
  3. #include "JsonObject.h"
  4. using namespace ArduinoJson::Generator;
  5. using namespace Microsoft::VisualStudio::CppUnitTestFramework;
  6. namespace JsonGeneratorTests
  7. {
  8. TEST_CLASS(Issue10)
  9. {
  10. struct Person {
  11. int id;
  12. char name[32];
  13. };
  14. Person persons[2];
  15. public:
  16. TEST_METHOD_INITIALIZE(Initialize)
  17. {
  18. Person boss;
  19. boss.id = 1;
  20. strcpy(boss.name, "Jeff");
  21. Person employee;
  22. employee.id = 2;
  23. strcpy(employee.name, "John");
  24. persons[0] = boss;
  25. persons[1] = employee;
  26. }
  27. TEST_METHOD(WrongWayToAddObjectInAnArray)
  28. {
  29. JsonArray<2> json;
  30. for (int i = 0; i < 2; i++)
  31. {
  32. JsonObject<2> object;
  33. object["id"] = persons[i].id;
  34. object["name"] = persons[i].name;
  35. json.add(object); // <- Adding a reference to a temporary variable
  36. }
  37. char buffer[256];
  38. json.printTo(buffer, sizeof(buffer));
  39. // the same values are repeated, that's normal
  40. Assert::AreEqual("[{\"id\":2,\"name\":\"John\"},{\"id\":2,\"name\":\"John\"}]", buffer);
  41. }
  42. TEST_METHOD(RightWayToAddObjectInAnArray)
  43. {
  44. JsonArray<2> json;
  45. JsonObject<2> object[2];
  46. for (int i = 0; i < 2; i++)
  47. {
  48. object[i]["id"] = persons[i].id;
  49. object[i]["name"] = persons[i].name;
  50. json.add(object[i]);
  51. }
  52. char buffer[256];
  53. json.printTo(buffer, sizeof(buffer));
  54. Assert::AreEqual("[{\"id\":1,\"name\":\"Jeff\"},{\"id\":2,\"name\":\"John\"}]", buffer);
  55. }
  56. };
  57. }