// // json_binder_polymorphic.t.h // json // // Created by Sam Jaffe on 11/14/18. // Copyright © 2018 Sam Jaffe. All rights reserved. // #include #include "json/json_binder.hpp" struct Base { virtual ~Base() = default; virtual void run() const = 0; }; struct Left : public Base { int a; void run() const override {} }; struct Right : public Base { std::string a; void run() const override {} }; bool operator==(Left const & lhs, Left const & rhs) { return lhs.a == rhs.a; } bool operator==(Right const & lhs, Right const & rhs) { return lhs.a == rhs.a; } using namespace json::binder; using namespace json::parser; class JsonBinderPolymorphicTest : public ::testing::Test { protected: using pBase = std::unique_ptr; polymorphic_binder & GetBinder() { static polymorphic_binder val = polymorphic_binder() ("Left", object_binder()("a", &Left::a)) ("Right", object_binder()("a", &Right::a)); return val; } }; using namespace ::testing; TEST_F(JsonBinderPolymorphicTest, CanHitLeftPolymorph) { char data[] = "{\"@id\":\"Left\", \"@value\":{\"a\":1}}"; pBase out; Left expected; expected.a = 1; EXPECT_NO_THROW(parse(json::binder::bind(out, GetBinder()), data)); EXPECT_THAT(&*out, Not(IsNull())); EXPECT_THAT(dynamic_cast(&*out), Not(IsNull())); EXPECT_THAT(dynamic_cast(*out), expected); } TEST_F(JsonBinderPolymorphicTest, CanHitRightPolymorph) { char data[] = "{\"@id\":\"Right\", \"@value\":{\"a\":\"hello\"}}"; pBase out; Right expected; expected.a = "hello"; EXPECT_NO_THROW(parse(json::binder::bind(out, GetBinder()), data)); EXPECT_THAT(&*out, Not(IsNull())); EXPECT_THAT(dynamic_cast(&*out), Not(IsNull())); EXPECT_THAT(dynamic_cast(*out), expected); }