Should I make a member function virtual just to make the class testable?

I am working on a class whose simplified version looks like this:

class Http_server {
public:
    void start(int port)
    {
        start_server();
        std::string content_type = extract_content_type(get_request());
    }

private:
    void start_server()
    {
        ...
    }

    std::string get_request()
    {
        ...
    }

    std::string extract_content_type(const std::string& request) const
    {
        ...
    }
};

Now I want to write a test case for extract_content_type. The problem is that it is closed, so I can not call it from the outside. The only function I can test is start, but it will actually start the server ( start_server) and wait for the request ( get_request).

As I can see, I have three options:

  • Make extract_content_typepublic
  • Extract extract_content_typeto utility class or namespace
  • Make start_serverit get_requestvirtual and create a mock object that overrides them.

- , , 3.

V8: http://code.google.com/p/v8/source/browse/trunk/test/cctest/test-date.cc

, , . virtual ++ :

  • / (, )
  • , .

? ? , , ? TDD , , extract_content_type, .

+5
6

, :

unit test

class Foo {
  public:
#ifdef UNITTEST
    friend class FooTest;
#endif
    ...

  protected:
    ...

  private:
    ...
};

: http://praveen.kumar.in/2008/01/02/how-to-unit-test-c-private-and-protected-member-functions/

+3

, . , ( , ).

, / . ​​ , , , .

TDD. , , , . , , , .

+3

API, . Typemock Isolator ++. , extract_content_type, ( , ), :

TEST_METHOD(TestExtractContentType)
    {   
        Http_server* server = new Http_server();

        std::string res ("result");
        PRIVATE_WHEN_CALLED(server, extract_content_type, NULL).Return(&res);

        std::string result;
        ISOLATOR_INVOKE_MEMBER(result, server, extract_content_type, NULL);

        PRIVATE_ASSERT_WAS_CALLED(server, extract_content_type);
        Assert::AreEqual(string("result"), result);
    }

. ISOLATOR_TESTABLE , .

ISOLATOR_TESTABLE std::string extract_content_type(const std::string& request) const 

. , .

+1

extract_content_type - , Http_server, . , , , . .

0

, , .

#define TESTING_VIRTUAL

virtual . , , virtual, , .

, private public , .

0

. , , . , , , , start? , , , , . !:)

, extract_content_type . .

0

All Articles