Add tests for RealmGateway, fix bugs.