1 /*
2  * %injeqt copyright begin%
3  * Copyright 2014 Rafał Malinowski (rafal.przemyslaw.malinowski@gmail.com)
4  * %injeqt copyright end%
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19  */
20 
21 #pragma once
22 
23 #include "provider.h"
24 
25 #include <functional>
26 #include <memory>
27 
28 using namespace injeqt::internal;
29 using namespace injeqt::v1;
30 
31 class mocked_provider : public provider
32 {
33 
34 public:
35 	explicit mocked_provider(type provided_type, types required_types, std::function<QObject *()> provide = [](){ return nullptr; }) :
36 		_provided_type{std::move(provided_type)},
37 		_required_types{std::move(required_types)},
38 		_provide{std::move(provide)},
39 		_object{nullptr}
40 	{}
~mocked_provider()41 	virtual ~mocked_provider() {}
42 
provided_type()43 	virtual const type & provided_type() const override { return _provided_type; };
44 
provide(injector_core &)45 	virtual QObject * provide(injector_core &) override
46 	{
47 		if (!_object)
48 			_object = _provide();
49 		return _object;
50 	};
51 
required_types()52 	virtual types required_types() const override { return _required_types; };
53 
require_resolving()54 	virtual bool require_resolving() const override { return true; }
55 
object()56 	QObject * object() const { return _object; }
57 
58 private:
59 	type _provided_type;
60 	types _required_types;
61 	std::function<QObject *()> _provide;
62 	QObject *_object;
63 
64 };
65 
66 template<typename T, typename... R>
make_mocked_provider()67 std::unique_ptr<mocked_provider> make_mocked_provider()
68 {
69 	return std::unique_ptr<mocked_provider>(new mocked_provider{make_type<T>(), types{make_type<R>()...}, [](){ return new T(); }});
70 }
71