有问题的代码
public void StartPlaying()
{
ThreadPool.QueueUserWorkItem(ignoredState =>
{
while (_playlist.Count > 0)
{
var audioFile = _playlist.Dequeue();
if (StartedPlaying != null)
StartedPlaying(this, new TypedAudioFileEventArgs(audioFile));
audioFile.SoundPlayer.PlaySync();
audioFile.SoundPlayer.Dispose();
if (StoppedPlaying != null)
StoppedPlaying(this, new TypedAudioFileEventArgs(audioFile));
}
});
}
和我的测试:
[TestMethod()]
public void StartPlayIsCalledTwice_OnlyRunningOnce()
{
int timeBetweenPlays = 0;
var target = new TypedAudioFilePlayer(timeBetweenPlays);
target.AddFile(TypedAudioFileCreator.CreateWord(1, "bl"));
target.StartedPlaying += StartedPlaying_Once;
target.StartPlaying();
target.StartPlaying();
}
private bool _once = false;
private void StartedPlaying_Once(object sender, TypedAudioFileEventArgs e)
{
if (!_once)
_once = true;
else
Assert.Fail("Should not be called more than once!");
}
我相信我的单元测试应该失败,根据 ThreadPool.QueueUserWorkItem 的 MSDN 描述来判断:
Queues a method for execution. The method executes when a thread pool thread becomes available.
默认线程池大小为 512,因此两个线程应立即可用于处理 StartPlaying 调用。我相信我的代码应该会失败,因为我没有提供任何保护措施来防止两个线程都可以访问同一资源的竞争条件。
这里发生了什么?
请您参考如下方法:
因为 StartedPlaying 事件仅在有要播放的项目时调用 StartPlaying 时才会引发。
_playlist.Dequeue(); 使您入队的文件出队。因此,当您第二次到达 while (_playlist.Count > 0) 时,它将立即失败,将第二次调用直接传递给 StartPlaying 而不会引发事件。
此外,正如 Bruno Silva 指出的那样,第二次调用 StartPlaying 生成的线程可能没有机会在测试退出之前执行任何操作。
就其值(value)而言,此代码中还有大约一百万至少 2 个线程错误:
// Where did _playlist come from? Is it shared state among the player threads?
// If so, all access to it should be in locks, since queues are not thread safe
while (_playlist.Count > 0)
// Both of these start threads and then immediately return.
// The test will probably exit before either of those threads do anything much
target.StartPlaying();
target.StartPlaying();
}
如果你想正确地进行单元测试,你需要定义前置条件、期望、 Action 和后置条件:
前提条件:您有一个已初始化的 TypedAudioFilePlayer,其中一个文件已排队:
var target = new TypedAudioFilePlayer(timeBetweenPlays);target.AddFile(TypedAudioFileCreator.CreateWord(1, "bl"));期望:如果两次调用 StartPlaying,则 StartedPlaying 事件只会引发一次
target.StartedPlaying += StartedPlaying_Once;操作: StartPlaying 方法将被调用两次:
target.StartPlaying();target.StartPlaying();后置条件:
StartedPlaying事件仅引发一次:private bool _once = false;private void StartedPlaying_Once(object sender, TypedAudioFileEventArgs e){如果(!_一次)_once = true;其他Assert.Fail("不应多次调用!");}
现在,您的测试成功了。这在这种情况下并不好,因为我在上面解释过。您需要通过消除队列错误和竞争条件使测试进入失败状态,然后努力使测试以正确的方式通过。
