开发者

How could I use google test on windows application based on message queue?

I want to use google test for my program that has timer functionality inside. The timer is implement by windows SetTimer(), and there is a message queue in the main() to process the timeout message.

while (GetMessage(&msg, NULL, 0, 0)) {
    if (msg.message == WM_TIMER) {
        ...
    }
    DispatchMessage(&msg);
}

For the google test, it calls RUN_ALL_TESTS() to start the testing.

int main( int argc , char *argv[] )
{
    testing::InitGoogleTest( &argc , argv );
    return RUN_ALL_TESTS();
}

My question is that how could 开发者_StackOverflow社区I integrate these two part. Because some function of my code will send out a message, I should have the same message queue mechanism to handle it.

Does that means I need to write the message queue handling in each test case? Is it a workable method?

TEST()
{
    ... message queue here ...
}

Is there any proper method to do this kind of test? Thank you all.


It seems that the code you want to test is dependent of a message queue mechanismn. You could improve testability, if you implement an abstract message handler class like this that gets injected into every class that needs to send a message:

class MessageHandler
{
  virtual void DispatchMessage(Msg messageToBeDispatched) = 0;
}

Now you could implement different message handlers for productiv and for testing purpose:

class TestMessageHandler : public MessageHandler
{
  void DispatchMessage(Msg messageToBeDispatched)
  {
     // Just testing, do nothing with this message, or just cout...
  }
}

class ProductiveMessageHandler : public MessageHandler
{
  void DispatchMessage(Msg messageToBeDispatched)
  {
     // Now do the real thing
  }
}

In your code you could now inject either a 'ProductiveMessageHandler' or a 'TestMessageHandler', or you could even use a mocked test handler using GoogleMock to test expectations.

class MyProductionCode
{
   MyProductionCode(MessageHandler *useThisInjectedMessageHandler);
}

Your testcode looks like that:

class TestMyProductionCode : public ::testing::Test
{
  TestMessageHandler myTestMessageHandler;
}

TEST(TestMyProductionCode, ExampleTest)
{
  MyProductionCode myTestClass(&myTestMessageHandler);

  ASSERT_TRUE(myTestClass.myTestFunction());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜