Skip to content

cpp-testing/mocks_injector

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

C++ Automatic Mocks Injector

Introduction

C++ Automatic Mocks Injector is C++14 header only library providing following functionality:

  • Automatically create required mocks
  • Automatically inject mocks to tested classes via constructor
  • Automatically register for required destructor's in case of smart pointers (supports testing of unique_ptr)
  • Uses HippoMocks as Mocking library
  • Uses DI as Dependency Injection library

Unit Tests

#include <string>
#include <memory>
#include <utility>

struct ilogger { virtual ~ilogger() { }; virtual void log(const std::string&) = 0; };
struct ilogic { virtual ~ilogic() { }; virtual void do_it() = 0; };

class example {
public:
    example(const std::shared_ptr<ilogger>& logger
          , std::unique_ptr<ilogic> logic
          , const std::string& text)
        : logger_(logger)
        , logic_(std::move(logic))
        , text_(text)
    { }

    int run() {
        logic_->do_it();
        logger_->log(text_);
        return 0;
    }

private:
    std::shared_ptr<ilogger> logger_;
    std::unique_ptr<ilogic> logic_;
    std::string text_;
};

#include <mocks_injector.hpp>

int main() {
    namespace di = boost::di;

    //1. create mocks injector and example class
    auto _ = di::make_injector<di::mocks_provider>();

    //2. set up expectations
    EXPECT_CALL(_, ilogic::do_it);
    EXPECT_CALL(_, ilogger::log).With("hello world");

    //3. run tests
    example sut{_, _, "hello world"};
    assert(0 == sut.run());
}

Integration Tests

struct logic : ilogic { void do_it() override { } };

class app {
public:
    app(std::shared_ptr<example> e)
        : example_(e)
    { }

    int run() {
        return example_->run();
    }

private:
    std::shared_ptr<example> example_;
};

#include <mocks_injector.hpp>

int main() {
    namespace di = boost::di;

    //1. create mocks injector with dependencies
    auto mi = di::make_injector<di::mocks_provider>(
        di::bind<std::string>.to("hello world")
      , di::bind<ilogic, logic> // inject real logic
    );

    //2. set up expectations
    EXPECT_CALL(mi, ilogger::log).With("hello world");

    //3. create example class and run it
    assert(!mi.create<app>().run());
}

License

Distributed under the Boost Software License, Version 1.0.

About

C++ Automatic Mocks Injector

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published