#include"Calculator.hpp"intCalculator::add(int a, int b) const {
return a + b;
}
intCalculator::multiply(int a, int b) const {
return a * b;
}
src/calculation/include/Calculator.hpp
#pragma once
classCalculator {
public:intadd(int a, int b) const ;
intmultiply(int a, int b) const ;
};
src/CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(project_src VERSION 1.0.0 LANGUAGES CXX)
set(TEST_BINARY_NAME "calculation"CACHESTRING"calculation")
message (STATUS"Building calculation")
add_executable(calculation)
target_sources(calculation PUBLIC${CMAKE_CURRENT_SOURCE_DIR}/calculation/Calculator.cpp
${CMAKE_CURRENT_SOURCE_DIR}/main.cpp
)
target_link_libraries(calculation
PUBLIC#test-core
)
target_include_directories(calculation
PUBLIC
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/calculation/include>
#$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/common/include>
)
target_compile_options(calculation
PUBLIC
-Wno-commentPRIVATE
-Werror=uninitialized
-Werror=return-type
)
install(TARGETS calculation RUNTIME DESTINATION"${CMAKE_INSTALL_BINDIR}"COMPONENTtest-service)
src/main.cpp
#include"Calculator.hpp"
#include<iostream>intmain () {
Calculator a;
auto b = a.add(10, 12);
std::cerr << " b = " << b << std::endl;
}
unittests/mocks/MockCalculator.hpp
#include<gmock/gmock.h>
#include<Calculator.hpp>classMockCalculator : publicCalculator {
public:MOCK_METHOD(int, add, (int a, int b), (const));
MOCK_METHOD(int, multiply, (int a, int b), (const));
};
unittests/tests/CalculatorTests.hpp
#include<gtest/gtest.h>
#include<gmock/gmock.h>using ::testing::_;
using ::testing::Return;
using ::testing::AtLeast;
using ::testing::MatcherInterface;
// using ::testing::MatcherResultListener;classCalculatorTestSuite : public ::testing::Test {
public:CalculatorTestSuite() {}
virtual~CalculatorTestSuite() {}
virtualvoidSetUp() {}
virtualvoidTearDown() {}
};
unittests/tests/CalculatorTestSuites.hpp
#include"CalculatorTests.hpp"
#include"MockCalculator.hpp"// Custom action to log addition resultsACTION_P(LogAddition, message) {
std::cout << message << arg0 << " + " << arg1 << std::endl;
}
// Custom matcher to check if a number is positiveMATCHER(IsPositive, "") { return arg > 0; }
// Custom matcher to check if greater than thresholdMATCHER_P(IsGreaterThan, threshold, "") { return arg > threshold; }
TEST_F(CalculatorTestSuite, AddOperation_tc1) {
Calculator calc;
EXPECT_THAT(calc.add(2, 3), IsPositive());
// Custom action usage is more applicable to mock objects
}
TEST_F(CalculatorTestSuite, AddOperation_tc2) {
MockCalculator calc;
EXPECT_CALL(calc, add(IsGreaterThan(10), _));
// EXPECT_CALL(calc, add(IsGreaterThan(10), _))// .WillOnce(LogAddition("Addition"));
calc.add(13, 14);
}
TEST_F(CalculatorTestSuite, MultiplyOperation) {
Calculator calc;
EXPECT_EQ(calc.multiply(3, 4), 12);
// Custom action usage is more applicable to mock objects
}