【问题标题】:Stopping a Poco::Thread for Unit Tests为单元测试停止 Poco::Thread
【发布时间】:2012-03-28 14:43:09
【问题描述】:

问题

我有一个 UDPlistener 应用程序,我需要为其编写单元测试。此侦听器持续侦听端口,并且始终在产品上运行。我们将 poco 库用于标准库中没有的框架。

现在我需要将它添加到单元测试应用程序中。

当前解决方案

我认为在运行应用程序的类RunApp 中实现Poco::Runnable 是最简单的。然后我可以在我的单元测试中创建一个新的Poco::Thread 来运行RunApp 类。

这行得通;我的侦听器正在运行,我可以在生成线程后在单元测试正文中发送测试消息。但是,我需要停止侦听器,以便其他单元测试可以运行。我添加了一条 UDP 消息,告诉侦听器杀死自己,但这仅用于单元测试和潜在的安全问题。

问题

有没有办法强制Poco::Thread 停止?还是我错误地构建了这个单元测试?我不希望侦听器在所有其他单元测试期间运行。

【问题讨论】:

    标签: c++ unit-testing poco-libraries


    【解决方案1】:

    如果不使用Poco::Thread 而使用Poco::Task,您将获得一个可以取消的线程。以下示例代码(准备好按原样运行)应该会给您一个想法:

    #include <Poco/Task.h>
    #include <Poco/TaskManager.h>
    #include <Poco/Thread.h>
    
    #include <string>
    #include <iostream>
    using namespace std;
    
    class UdpListenerTask : public Poco::Task {
    public:
        UdpListenerTask(const string& name) : Task(name) { }
    
        void runTask() {
            cout << name() << ": starting" << endl;
            while (! isCancelled()) {
                // Do some work. Cannot block indefinitely, otherwise it
                // will never test the isCancelled() condition.
                doSomeWork();
            }
            cout << endl << name() << ": cancelled " << endl;
        }
    private:
        int doSomeWork() {
            cout << "*" << flush;
            // Simulate some time spent doing work
            int i;
            for (i = 0; i < INT32_MAX/1000; i++) { }
            return i;
        }
    };
    
    void runUdpProbe() {
        // Simulate some time spent running the probe.
        Poco::Thread::sleep(1000);
    }
    
    int main() {
        Poco::TaskManager tm;
        UdpListenerTask* st = new UdpListenerTask("task1");
        tm.start(st); // tm takes ownership
    
        // Run test 1.
        runUdpProbe();
        // Test 1 done. Cancel the UDP listener
        st->cancel();
    
        // Run all the other tests
    
        // cleanup
        tm.joinAll();
        return 0;
    }
    

    POCO 幻灯片 Multithreading 给出了 Poco::Thread 和 Poco::Task 的用法示例。

    顺便说一句,单元测试应该通过抽象类和模拟对象绕过 UDP 通信;我认为这个测试应该被称为特性测试:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      相关资源
      最近更新 更多