| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- //
- // json_binder_polymorphic.t.h
- // json
- //
- // Created by Sam Jaffe on 11/14/18.
- // Copyright © 2018 Sam Jaffe. All rights reserved.
- //
- #include <gmock/gmock.h>
- #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<Base>;
- polymorphic_binder<pBase> & GetBinder() {
- static polymorphic_binder<pBase> val = polymorphic_binder<pBase>()
- ("Left", object_binder<Left>()("a", &Left::a))
- ("Right", object_binder<Right>()("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<Left*>(&*out), Not(IsNull()));
- EXPECT_THAT(dynamic_cast<Left&>(*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<Right*>(&*out), Not(IsNull()));
- EXPECT_THAT(dynamic_cast<Right&>(*out), expected);
- }
|