online run
#include <gtest/gtest.h>
#include <gmock/gmock.h>
class FooInterface {
public:
virtual ~FooInterface() {
}
virtual std::string getArbitraryString() = 0;
virtual int getPosition(int n) = 0;
virtual void setValue(std::string& value){};
virtual void setDoubleValues(int x, int y){};
};
class MockFoo : public FooInterface {
public:
MOCK_METHOD0(getArbitraryString,std::string());
MOCK_METHOD1(getPosition,int(int));
MOCK_METHOD1(setValue, void(std::string& value));
MOCK_METHOD2(setDoubleValues, void(int x, int y));
};
TEST(TestField, foo) {
MockFoo mockFoo;
EXPECT_CALL(mockFoo, getArbitraryString())
.Times(1)
.WillOnce(::testing::Return("Hello World!"));
std::string returnValue = mockFoo.getArbitraryString();
EXPECT_CALL(mockFoo, getPosition(1))
.Times(::testing::AtLeast(1))
.WillOnce(::testing::Return(100))
.WillRepeatedly(::testing::Return(200));
int val = mockFoo.getPosition(1);
val = mockFoo.getPosition(1);
val = mockFoo.getPosition(1);
val = mockFoo.getPosition(1);
}
online run turlte
online run window
#include <iostream>
#include <stdexcept>
#include <chrono>
#include <thread>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
namespace windows {
enum class Severity { LOW, MEDIUM, CRITICAL };
bool troubleshooting_tool(Severity severity)
{
std::cout << "Looking for solution... \n";
std::this_thread::sleep_for(std::chrono::seconds(2000));
throw std::runtime_error {"System Windows cannot find the solution."};
}
}
struct AdvancedTroubleshootingTool {
void FixMonitorDriver()
{
try {
predicate(windows::Severity::CRITICAL);
} catch (const std::exception& ex)
{
std::cout << "Success: " << ex.what() << "\n";
throw;
}
}
std::function<bool(windows::Severity)> predicate = &windows::troubleshooting_tool;
};
TEST(AdvancedTroubleshootingToolTest, DoesNotFixMonitorDriver)
{
::testing::MockFunction<bool(windows::Severity)> windowsTrouleshootingMock{};
EXPECT_CALL(windowsTrouleshootingMock, Call(windows::Severity::CRITICAL))
.WillOnce(::testing::Throw(std::runtime_error{"Exception thrown from mock."}));
AdvancedTroubleshootingTool unit_under_test{ windowsTrouleshootingMock.AsStdFunction() };
EXPECT_THROW(unit_under_test.FixMonitorDriver(), std::exception);
}