为什么 Rhino Mocks 在与线程一起使用时会抛出异常?
在使用 Rhino Mocks 和 Threads 时,我们遇到了一个奇怪的问题。我已经 试图隔离问题,但现在我坚持这一点:
[TestClass]
public class FoolTests
{
[TestMethod]
public void TestMethod_Scenario_Result()
{
for (int i = 0; i < 5; i++)
{
var fool = MockRepository.GenerateStub<IFool>();
fool.Stub(x => x.AmIFool).Return(false);
new Fool(fool);
}
}
}
public class Fool
{
private readonly IFool _fool;
private readonly Thread _thread;
public Fool(IFool fool)
{
_fool = fool;
_thread = new Thread(Foolish);
_thread.Start();
}
private void Foolish()
{
while (true)
{
var foo = _fool.Foolness;
}
}
}
public interface IFool
{
bool AmIFool { get; }
bool Foolness { get; set; }
}
运行此测试时几乎所有时间,我都会得到“测试方法 FoolTests.TestMethod_Scenario_Result 抛出异常:System.InvalidOperationException:当模拟对象处于重播中时,此操作无效状态。”在线“fool.Stub(x => x.AmIFool).Return(false);”。
我不知道这里出了什么问题。有人有想法吗?或者我必须深入研究 Rhino Mocks 代码吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定这是否是一个完整的答案,但此页面有一个关于多线程的有趣注释:
http://www.ayende.com/projects/rhino-mocks/api/files/MockRepository-cs.html
我要尝试的第一件事是设置所有模拟和期望,然后执行构造函数。这似乎对我有用:
由于此代码有效,我想问题是您在一个线程中进行播放,同时在另一个线程中进行录制(针对不同的存根)。即使您在不同的存根上操作,同时播放和录制似乎也不是线程安全的。
Not sure if this is a complete answer, but this page has an interesting note on multi-threading:
http://www.ayende.com/projects/rhino-mocks/api/files/MockRepository-cs.html
First thing I'd try is setting up all mocks and expectations, then executing your constructors. This seems to be working for me:
Since this code works, I imagine the problem is that you are doing playback in one thread while recording (for a different stub) in another thread. Playing back and recording at the same time seems like it isn't thread safe, even if you're operating on different stubs.