Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / DevOps / testing

Redirecting std::clog to Test Framework Output

2.86/5 (3 votes)
20 Jun 2016CPOL 8.4K  
Wrap writing to the test logger with std::streambuf then substitute in std::clog

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:

C++
#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

C++
// Initialise then swap
newBuffer = std::make_shared<TestUtils::LogStream>();
oldBuffer = std::clog.rdbuf(newBuffer.get());
std::clog << "Entering Tests" << std::endl;

// Run the tests
// ...

// Swap and free
std::clog << "Exiting Tests" << std::endl;
std::clog.rdbuf(oldBuffer);
newBuffer = nullptr;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)