Introduction
You may have code that usually writes to std::cout
, etc. but is lost in when using a test framework. This tip extracts some code from my article on using Gherkin DSL to show how a test frameworks' logging function can be wrapped and substituted into std::clog
, std::cout
, etc. to enhance the test log.
The Wrapper
The content of LogStream.h is a class containing a buffer and two overloaded functions:
#pragma once
#include "stdafx.h"
#include "CppUnitTest.h"
#include <vector>
namespace TestUtils
{
class LogStream : public std::streambuf
{
std::vector<char> buffer;
int_type overflow(int_type ch)
{
if (ch != traits_type::eof())
buffer.push_back(ch);
return ch;
}
int sync()
{
if (buffer.back() == '\n')
buffer.pop_back();
buffer.emplace_back('\0');
Microsoft::VisualStudio::CppUnitTestFramework::Logger::WriteMessage(&buffer[0]);
buffer.clear();
return 0;
}
};
}
Usage
newBuffer = std::make_shared<TestUtils::LogStream>();
oldBuffer = std::clog.rdbuf(newBuffer.get());
std::clog << "Entering Tests" << std::endl;
std::clog << "Exiting Tests" << std::endl;
std::clog.rdbuf(oldBuffer);
newBuffer = nullptr;