-
Notifications
You must be signed in to change notification settings - Fork 0
/
testStreamOutput.cpp
43 lines (31 loc) · 1008 Bytes
/
testStreamOutput.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
testStreamOutput.cpp
Tests the output of an error message from a function.
While the example is for std::cerr (standard error), the approach
works for any std::ostream, including std::cout (standard output).
*/
#include <iostream>
#include <sstream>
#include <cassert>
// ensure assert() is not turned off
#ifdef NDEBUG
static_assert(false, "NDEBUG cannot be defined");
#endif
// writes to standard error
void process() {
std::cerr << "Error message" << '\n';
}
int main() {
// save the original stream buffer of std::cerr
std::streambuf* originalStreamBuffer = std::cerr.rdbuf();
// redirect std::cerr to a stringstream
std::ostringstream errorCapture;
std::cerr.rdbuf(errorCapture.rdbuf());
// call the function that writes to standard error
process();
// restore the original buffer of std::cerr
std::cerr.rdbuf(originalStreamBuffer);
// test the error message
assert(errorCapture.str() == "Error message\n");
return 0;
}