Click here to Skip to main content
15,886,067 members
Articles / DevOps / Testing
Tip/Trick

Redirecting std::clog to Test Framework Output

Rate me:
Please Sign up or sign in to vote.
2.86/5 (3 votes)
20 Jun 2016CPOL 8.1K   3  
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)


Written By
United Kingdom United Kingdom
Mathematician turned freelance Software Engineer with over 20 years experience, mainly in the development of CAD/CAM/CAE software. Generally worked for smaller businesses - although have been at Lloyd's Register, Siemens and Rolls-Royce. Enjoy living on the edge of the Peak District where I go cycling and hiking.

Comments and Discussions

 
-- There are no messages in this forum --