json_binder_polymorphic_test.cxx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //
  2. // json_binder_polymorphic.t.h
  3. // json
  4. //
  5. // Created by Sam Jaffe on 11/14/18.
  6. // Copyright © 2018 Sam Jaffe. All rights reserved.
  7. //
  8. #include <gmock/gmock.h>
  9. #include "json/json_binder.hpp"
  10. struct Base {
  11. virtual ~Base() = default;
  12. virtual void run() const = 0;
  13. };
  14. struct Left : public Base {
  15. int a;
  16. void run() const override {}
  17. };
  18. struct Right : public Base {
  19. std::string a;
  20. void run() const override {}
  21. };
  22. bool operator==(Left const & lhs, Left const & rhs) {
  23. return lhs.a == rhs.a;
  24. }
  25. bool operator==(Right const & lhs, Right const & rhs) {
  26. return lhs.a == rhs.a;
  27. }
  28. using namespace json::binder;
  29. using namespace json::parser;
  30. class JsonBinderPolymorphicTest : public ::testing::Test {
  31. protected:
  32. using pBase = std::unique_ptr<Base>;
  33. polymorphic_binder<pBase> & GetBinder() {
  34. static polymorphic_binder<pBase> val = polymorphic_binder<pBase>()
  35. ("Left", object_binder<Left>()("a", &Left::a))
  36. ("Right", object_binder<Right>()("a", &Right::a));
  37. return val;
  38. }
  39. };
  40. using namespace ::testing;
  41. TEST_F(JsonBinderPolymorphicTest, CanHitLeftPolymorph) {
  42. char data[] = "{\"@id\":\"Left\", \"@value\":{\"a\":1}}";
  43. pBase out;
  44. Left expected; expected.a = 1;
  45. EXPECT_NO_THROW(parse(json::binder::bind(out, GetBinder()), data));
  46. EXPECT_THAT(&*out, Not(IsNull()));
  47. EXPECT_THAT(dynamic_cast<Left*>(&*out), Not(IsNull()));
  48. EXPECT_THAT(dynamic_cast<Left&>(*out), expected);
  49. }
  50. TEST_F(JsonBinderPolymorphicTest, CanHitRightPolymorph) {
  51. char data[] = "{\"@id\":\"Right\", \"@value\":{\"a\":\"hello\"}}";
  52. pBase out;
  53. Right expected; expected.a = "hello";
  54. EXPECT_NO_THROW(parse(json::binder::bind(out, GetBinder()), data));
  55. EXPECT_THAT(&*out, Not(IsNull()));
  56. EXPECT_THAT(dynamic_cast<Right*>(&*out), Not(IsNull()));
  57. EXPECT_THAT(dynamic_cast<Right&>(*out), expected);
  58. }