如何在windows应用程序上使用基于消息队列的谷歌测试

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

本文关键字:消息 队列 测试 谷歌 于消息 windows 应用 应用程序 程序上      更新时间:2023-10-16

我想使用谷歌测试我的程序,里面有定时器功能。定时器由windows SetTimer()实现,并且在main()中有一个消息队列来处理超时消息。

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

对于google测试,它调用RUN_ALL_TESTS()来启动测试。

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

我的问题是如何把这两部分结合起来。因为我的代码中的某些函数会发出消息,所以我应该使用相同的消息队列机制来处理它。

这是否意味着我需要在每个测试用例中编写消息队列处理?这是一个可行的方法吗?

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

有什么合适的方法来做这种测试吗?谢谢大家。

您想要测试的代码似乎依赖于消息队列机制。你可以提高可测试性,如果你实现一个抽象的消息处理程序类,像这样被注入到每一个需要发送消息的类:

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

现在您可以实现不同的消息处理程序,用于生产和测试目的:

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
  }
}

在你的代码中,你现在可以注入一个'ProductiveMessageHandler'或'TestMessageHandler',或者你甚至可以使用一个模拟的测试处理程序使用GoogleMock来测试期望。

class MyProductionCode
{
   MyProductionCode(MessageHandler *useThisInjectedMessageHandler);
}

你的testcode看起来像这样:

class TestMyProductionCode : public ::testing::Test
{
  TestMessageHandler myTestMessageHandler;
}
TEST(TestMyProductionCode, ExampleTest)
{
  MyProductionCode myTestClass(&myTestMessageHandler);
  ASSERT_TRUE(myTestClass.myTestFunction());
}