Unit function testing for side effects

How do you unit test do_int_to_string_conversion?

#include <string>
#include <iostream>

void do_int_to_string_conversion(int i, std::string& s) {
    switch(i) {
    case 1:
        s="1";
        break;
    case 2:
        s="2";
        break;
    default:
        s ="Nix";
    }
}

int main(int argc, char** argv){
    std::string little_s;

    do_int_to_string_conversion(1, little_s);
    do_int_to_string_conversion(2, little_s);
    do_int_to_string_conversion(3, little_s);

}
+5
source share
5 answers

I assume this is just an example. Why can't you claim the value of little_s after every call?

do_int_to_string_conversion(1, little_s);
assert_are_equal("1", little_s);
+9
source

Instead of worrying about how to test the function in its current form, I would revise the function to work a little smarter, and instead test the redesigned version.

, , ( ) : , . , (std::cout), - , (, GUI, , ).

1) 2) .

std::string convert_int(int val) {
    switch (val) { 
       case 1: return "1";
       case 2: return "2";
       default: return "Nix";
   }
}

std::ostream &write_string(std::ostream &os, std::string const &s) { 
    return os << s;
}

() - , convert_int , , , .

, write_string - , , , . - convert_int , . write_string stringstream ostream - .str(), , ( ) , .

+11

, , std::cout std::ostream .

, :

#if PRODUCTION
std::ostream my_output = std::cout;
#else
std::ostream my_output = std::ostringstream;
#endif

void setup()
{
    my_output = std::ostringstream;
}

void print_hello()
{
    my_output << "hello";
}

void test_hello_was_printed()
{
    print_hello();
    ASSERT("hello" == my_output.str());
}

- .

+3

do_int_to_string_conversion , ( ).

void do_int_to_string_conversion(int i, std::string& s) {
    switch(i) { ... }
}

, unit test, .

If I need a function that printed the result of the conversion, I would put it in a separate function, and I would parameterize the output stream.

void output_int(int i, ostream &stream) {
    std::string s;
    do_int_to_string_conversion(i, s);
    stream << s;
}

To unit test, I would pass the std :: stringstream object and check the result.

+3
source

You can use something like Expect to give it some input and make sure its output is what it should be.

-1
source

All Articles