无法使用Rhino mock模拟异步服务行为

时间:2011-03-08 11:57:40

标签: c# silverlight unit-testing silverlight-4.0 rhino-mocks

我尝试模拟(使用Rhyno mock)同步服务的行为。

这是一个例子:我得到了一个名为void GetServerState()的方法的服务。由于此方法是同步的,因此它是无效的,但是当它被调用时,它将调用代理并调用事件GetServerStateCompleted(object,eventargs)。 在这一点上,我希望每个人都跟着我; - )

现在,让我们看一下mock(它实际上是一个存根,但没关系)

public class MyStub
{
 protected MockRepository MockRepository {get;set;}
 public IMyService MyService {get;set;} //the service with GetServerState() Method
 protected delegate void DelegateVoid(); //for easy writting

 public MyStub()
 {
   MockRepository = new MockRepository ();
   MyService = MockRepository.Stub<IMyService >();

   //And now, let's try to mock the behaviour
   MyService.Stub(sm => sm.GetServerState())
                .IgnoreArguments()
                .Do((DelegateVoid)GetServerStateCompletedBehaviour);
 }

 //the method that should be launched when someone call GetServerState on the Stub
 protected void GetServerStateCompletedBehaviour()
 {
  MyService.Raise(x=>x.GetServerStateCompleted+=null,MyService,new EventArgs());
 }
}

//And here is how I would like to use it
[TestMethod]
void Test()
{
 try
 {
  IMyService Stub = new MyStub().MyService;
  Stub += new EventHandler(EventMethod);
  Stub.GetServerState();
  Assert.Fail();
 }
 catch(MyException){}
}

void EventMethod(Object sender, EventArgs e)
{
 Throw new MyException();
}

因为一切似乎都适合我,这段代码根本不起作用。是否有人开始解释为什么它不起作用?

THX,

1 个答案:

答案 0 :(得分:1)

我发现了什么问题:

public MyStub()
 {
   MockRepository = new MockRepository ();
   //MyService = MockRepository.Stub<IMyService >(); //Stupid Stupid Stupid !!!
   MyService = MockRepository.GenerateStub<IMyService >();

   //And now, let's try to mock the behaviour
   MyService.Stub(sm => sm.GetServerState())
                .IgnoreArguments()
                .Do((DelegateVoid)GetServerStateCompletedBehaviour);
 }