NSubstitute与PRISM EventAggregator:断言调用方法会触发具有正确有效负载的事件 [英] NSubstitute vs PRISM EventAggregator: Assert that calling a method triggers event with correct payload

查看:59
本文介绍了NSubstitute与PRISM EventAggregator:断言调用方法会触发具有正确有效负载的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下更新人员并通过PRISM EventAggregator发布事件以表明该人员已更新的方法.

Consider the below method that updates a person and publishes an event through the PRISM EventAggregator to indicate that the person has been updated.

我想对消息以正确的有效负载发送进行单元测试.在这种情况下,这意味着正确的personId.

I would like to unit test that the message is sent with the correct payload. In this case that would mean the correct personId.

public void UpdatePerson(int personId)
{
    // Do whatever it takes to update the person
    // ...

    // Publish a message indicating that the person has been updated
    _eventAggregator
        .GetEvent<PersonUpdatedEvent>()
        .Publish(new PersonUpdatedEventArgs
        {
            Info = new PersonInfo
            {
                Id = personId,
                UpdatedAt = DateTime.Now
            };
        });
}

我知道我可以为事件聚合器创建一个替代品:

I know that I can create a substitute for the event aggregator:

var _eventAggregator = Substitute.For<IEventAggregator>();

但是,我不知道如何检测消息的发送时间以及如何检查其有效载荷.

However, I don't know how to detect when a message is sent and how to check its payload.

推荐答案

我不是一位经验丰富的单元测试人员,所以我不确定这是否是编写的正确单元测试.但是无论如何,到目前为止,这就是我对其进行测试的方式,并且似乎可以满足我的要求.

I'm not an experienced unit tester so I'm not sure this is the correct unit test to write. But anyway, this is how I tested it so far and it seems to do what I want.

[Test]
public void TestPersonUpdateSendsEventWithCorrectPayload()
{
    // ARRANGE
    PersonUpdatedEventArgs payload = null;
    _eventAggregator
        .GetEvent<PersonUpdatedEvent>()
        .Subscribe(message => payload = message);

    // ACT
    _personService.UpdatePerson(5);

    // ASSERT
    payload.Should().NotBeNull();
    payload.Id.Should().Be(5);
}

欢迎反馈.

这篇关于NSubstitute与PRISM EventAggregator:断言调用方法会触发具有正确有效负载的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆