停止Poco::Thread用于单元测试

3

问题

我有一个UDP监听应用程序,需要编写一个单元测试。该监听器不断侦听端口,并且旨在始终在产品上运行。我们使用poco库来进行标准库之外的框架。

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

当前解决方案

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

这个方法可行;我的监听器正在运行,我可以在线程生成后在单元测试主体中发送测试消息。但是,我需要停止监听器以便其他单元测试可以运行。我添加了一个UDP消息,告诉监听器自杀,但这只被单元测试使用,可能存在安全问题。

问题

有没有一种方法可以强制停止Poco::Thread?或者我错了吗?我不希望监听器在所有其他单元测试期间运行。

1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
8
如果您使用 Poco::Task 而不是使用 Poco::Thread,您将获得一个可以被取消的线程。以下示例代码(已准备好运行)应该会给您一个想法:
#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通信;我认为这个测试应该被称为功能测试 :-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,