Skip to main content
 首页 » 编程设计

c#之如何测试阻塞功能

2024年02月06日14JustinYoung

如何测试某个函数在特定情况下是否无限期阻塞?

[Test] 
public void BlockingTest() 
{ 
    blockingFunction();    // this function halts execution indefinitely 
 
    Assert.Fail("Execution not halted."); 
} 

假设 blockingFunction() 是一个等待某事发生的函数,它应该阻止执行直到特定事件发生,并且测试假设该事件永远不会发生。

编辑:我实际上正在寻找的是一个优雅的解决方案,可能无需在报告成功之前明确等待硬编码时间。

贴出我的现状供引用:

[Test] 
public void BlockTest() { 
    BytesStream bs = new BytesStream(); 
    bs.Write(new byte[] { 1, 2 }, 0, 2); 
 
    var buff2 = new byte[2]; 
    bs.Read(buff2, 0, 2); 
 
    bool dataWritten = false; 
 
    new Thread(() => { 
        for(int i=0; i<100; i++) 
            Thread.Sleep(0); // ensure the parent thread execute next line 
 
        dataWritten = true; 
        bs.Write(new byte[] { 3, 4 }, 0, 2); 
    }).Start(); 
 
    Assert.AreNotEqual(0, bs.Read(buff2, 0, 2), "#1"); 
 
    if(!dataWritten) 
        Assert.Fail("#2"); 
 
    Assert.AreEqual(new byte[] { 3, 4 }, buff2, "#3"); 
} 

请您参考如下方法:

How do I test if a function blocks indefinitely in a particular situation?

这叫做 Halting Problem .已证明无法解决。