I am not 100% sure that this is SO-adequate question, but I guess it falls under "a specific programming problem". Tips to make it more SO-friendly are welcome.
一点背景
在 DLang 中,线程之间没有默认的数据共享——取而代之的是我们使用消息传递。这种方法既安全又干净,但很难水平扩展我们的代码。最好的例子是多作者 - 多读者问题 - 使用 std.concurrency
时会变得相当复杂。
解决该问题的常见方法是使用内存中队列 - 写入者推送到该队列,读者从中拉出,每个线程按自己的节奏运行,Bob 是你的叔叔。因此,我决定自己为 DLang 实现 Queue。
代码
队列有以下 API:
module javaesque.concurrency;
Queue!T queue(T)(){
// constructor, out of struct itself for implementation sake
}
struct Queue(T){
// internals not important for the sake of question
void push(T val){
// ...
}
T pull(){
// ...
}
}
这是一个使用它的示例应用程序:
// import whatever's needed, stdio, concurrency, etc
void runnable(Queue!string q){
try {
while (true) {
writeln(to!string(thisTid)~" "~q.pull());
}
} catch (OwnerTerminated ot) {
}
}
void main(string[] args){
Queue!string queue = queue!string();
spawn(&runnable, queue);
spawn(&runnable, queue);
for (int i = 0; i< 20; ++i){
queue.push(to!string(i));
}
readln();
}
问题
好的,那我该如何测试呢?在制作原型(prototype)时,我只是通过运行该示例应用程序对其进行了测试,但既然我已经确认这个想法本身可以按预期工作,我想编写一些单元测试。但是如何呢?
Please keep in mind that I didn't add
dlang
or related tags to this question. Even though I've supplied snippets in DLang and the background is highly D-related, I am looking for general help on testing this kind of structures, without constraining myself to this language. Obviously, general answer with DLang-specific addition is welcome, but the question itself should be treated as language-agnostic.
最佳答案
好吧,“通用”测试方法有两个方面:
- 您专注于构造的公共(public)契约,并想出测试该契约各个方面的测试用例
- 您专注于内部实现并考虑(额外的)测试用例以让您进入特定的极端情况
除此之外:您显然首先以单线程方式测试整个构造。您还可以查看与 same thread 类似的内容服务:您将环境设置为有效仅使用一个线程。
这对于您的“大部分”代码可能就足够了 - 然后您可能会接受一些实际测试一个预期端到端场景(使用多线程)的“集成”测试。例如,您可以在那里测试您的多个读者最终会收到一些预期的结果。
最后,从另一个角度来看:好的单元测试的关键是编写可以容易进行单元测试的代码。你需要能够真正地孤立地看待你的不同单位。但是,如果您要在此处提供该代码,那宁愿变成一个代码审查请求(不属于此处)。
关于multithreading - 如何测试跨线程队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46150452/