验证模拟对象引发了事件

发布于 2024-09-04 07:31:32 字数 1938 浏览 5 评论 0原文

在我的单元测试中,如何验证模拟对象是否引发了事件。

我有一个视图(UI)-->视图模型 -->数据提供者 -->服务代理。 ServiceProxy 对服务操作进行异步调用。当异步操作完成时,将调用 DataProvider 上的方法(回调方法作为方法参数传递)。然后回调方法引发 ViewModel 正在侦听的事件。

对于 ViewModel 测试,我模拟 DataProvider 并验证 DataProvider 引发的事件的处理程序是否存在。在测试 DataProvider 时,我模拟了 ServiceProxy,但是如何测试调用回调方法并引发事件。

我正在使用 RhinoMock 3.5 和 AAA 语法

谢谢

-- DataProvider --

public partial class DataProvider
{
    public event EventHandler<EntityEventArgs<ProductDefinition>> GetProductDefinitionCompleted;

    public void GetProductDefinition()
    {
        var service = IoC.Resolve<IServiceProxy>();
        service.GetProductDefinitionAsync(GetProductDefinitionAsyncCallback);
    }

    private void GetProductDefinitionAsyncCallback(ProductDefinition productDefinition, ServiceError error)
    {
        OnGetProductDefinitionCompleted(this, new EntityEventArgs<ProductDefinition>(productDefinition, error));
    }

    protected void OnGetProductDefinitionCompleted(object sender, EntityEventArgs<ProductDefinition> e)
    {
        if (GetProductDefinitionCompleted != null)
            GetProductDefinitionCompleted(sender, e);
    }
}

-- ServiceProxy --

public class ServiceProxy : ClientBase<IService>, IServiceProxy
{
    public void GetProductDefinitionAsync(Action<ProductDefinition, ServiceError> callback)
    {
        Channel.BeginGetProductDefinition(EndGetProductDefinition, callback);
    }

    private void EndGetProductDefinition(IAsyncResult result)
    {
        Action<ProductDefinition, ServiceError> callback =
            result.AsyncState as Action<ProductDefinition, ServiceError>;

        ServiceError error;
        ProductDefinition results = Channel.EndGetProductDefinition(out error, result);

        if (callback != null)
            callback(results, error);
    }
}

In my unit test how can I verify that an event is raised by the mocked object.

I have a View(UI) --> ViewModel --> DataProvider --> ServiceProxy. ServiceProxy makes async call to serivce operation. When async operation is complete a method on DataProvider is called (callback method is passed as a method parameter). The callback method then raise and event which ViewModel is listening to.

For ViewModel test I mock DataProvider and verify that handler exists for event raised by DataProvider. When testing DataProvider I mock ServiceProxy, but how can I test that callback method is called and event is raised.

I am using RhinoMock 3.5 and AAA syntax

Thanks

-- DataProvider --

public partial class DataProvider
{
    public event EventHandler<EntityEventArgs<ProductDefinition>> GetProductDefinitionCompleted;

    public void GetProductDefinition()
    {
        var service = IoC.Resolve<IServiceProxy>();
        service.GetProductDefinitionAsync(GetProductDefinitionAsyncCallback);
    }

    private void GetProductDefinitionAsyncCallback(ProductDefinition productDefinition, ServiceError error)
    {
        OnGetProductDefinitionCompleted(this, new EntityEventArgs<ProductDefinition>(productDefinition, error));
    }

    protected void OnGetProductDefinitionCompleted(object sender, EntityEventArgs<ProductDefinition> e)
    {
        if (GetProductDefinitionCompleted != null)
            GetProductDefinitionCompleted(sender, e);
    }
}

-- ServiceProxy --

public class ServiceProxy : ClientBase<IService>, IServiceProxy
{
    public void GetProductDefinitionAsync(Action<ProductDefinition, ServiceError> callback)
    {
        Channel.BeginGetProductDefinition(EndGetProductDefinition, callback);
    }

    private void EndGetProductDefinition(IAsyncResult result)
    {
        Action<ProductDefinition, ServiceError> callback =
            result.AsyncState as Action<ProductDefinition, ServiceError>;

        ServiceError error;
        ProductDefinition results = Channel.EndGetProductDefinition(out error, result);

        if (callback != null)
            callback(results, error);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半衾梦 2024-09-11 07:31:32

听起来您需要编写两个不同的单元测试:

  1. Service Proxy 单元测试:此测试将确保在异步调用完成时调用发送到 ServiceProxy 的回调。

  2. 数据提供程序单元测试:此测试将确保当调用某个方法时,会引发一个事件(假设有一些订阅者)。

    数据提供程序单元测试

您正在寻求哪一方面的帮助?

编辑:

对于第 1 项,我认为您不需要任何嘲笑。只需提供一个回调,在调用时将某些变量设置为 true:

// arrange
IServiceProxy serviceProxy = new ServiceProxy();
bool callbackMade;

// act
serviceProxy.GetDataAsync(() => callbackMade = true);

// assert
Assert.IsTrue(callbackMade);

对于第 2 项,只需订阅单元测试中的事件并确保调用该事件:

// arrange
DataProvider dp = new DataProvider();
bool eventRaised;
dp.DataReturned += (s,e) => eventRaised = true;

// act
dp.DoSomethingThatShouldRaiseEvent();

// assert
Assert.IsTrue(eventRaised)

我不知道您的事件/回调的签名,因此我只是做了一些猜测。

It sounds like you have two different unit tests to write:

  1. Service Proxy unit test: This test will make sure that the callback sent in to the ServiceProxy will be called upon completion of the async call.

  2. Data Provider unit test: This test will make sure that when a certain method is called, an event is raised (assuming there were some subscribers).

Which one are you looking for help on?

EDIT:

For item #1, I don't see that you'd need any mocking. Simply provide a callback that sets some variable to true when called:

// arrange
IServiceProxy serviceProxy = new ServiceProxy();
bool callbackMade;

// act
serviceProxy.GetDataAsync(() => callbackMade = true);

// assert
Assert.IsTrue(callbackMade);

For item #2, again, just subscribe to the event in your unit test and make sure the event is called:

// arrange
DataProvider dp = new DataProvider();
bool eventRaised;
dp.DataReturned += (s,e) => eventRaised = true;

// act
dp.DoSomethingThatShouldRaiseEvent();

// assert
Assert.IsTrue(eventRaised)

I don't know the signatures of your events/callbacks so I just made some guesses.

柠檬色的秋千 2024-09-11 07:31:32

以下示例设置一个 IService 存根,该存根将在调用 IService.AsyncOperationWithCallBack(Action callBack) 时简单地调用传递给它的任何回调。

// arrange
var serviceStub = MockRepository.GenerateStub<IService>();
serviceStub.Stub(x => x.AsyncOperationWithCallBack(Arg<Action>.Is.NotNull))
    .WhenCalled(
        invokation =>
        {
            var callback = (Action)invokation.Arguments[0];
            callback();
        });

var dataProvider = new DataProvider(serviceStub);  

// act
bool raised = false;
dataProvider.MyEvent += delegate { raised = true; };
dataProvider.DoSomething();

// assert
serviceStub.AssertWasCalled(
    x=>x.AsyncOperationWithCallBack(Arg<Action>.Is.NotNull));
Assert.IsTrue(raised);

The following example sets up an IService stub which will simply invoke any callback that is passed to it when IService.AsyncOperationWithCallBack(Action callback) is called.

// arrange
var serviceStub = MockRepository.GenerateStub<IService>();
serviceStub.Stub(x => x.AsyncOperationWithCallBack(Arg<Action>.Is.NotNull))
    .WhenCalled(
        invokation =>
        {
            var callback = (Action)invokation.Arguments[0];
            callback();
        });

var dataProvider = new DataProvider(serviceStub);  

// act
bool raised = false;
dataProvider.MyEvent += delegate { raised = true; };
dataProvider.DoSomething();

// assert
serviceStub.AssertWasCalled(
    x=>x.AsyncOperationWithCallBack(Arg<Action>.Is.NotNull));
Assert.IsTrue(raised);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文