Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

c# - NSubstitute vs PRISM EventAggregator: Assert that calling a method triggers event with correct payload

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

Feedback welcome.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...