如何在Wpf Prism库中测试传递给PubSubEvent的subscription方法的方法?

时间:2019-01-04 13:46:18

标签: moq prism

我有两个ViewModel, MainWindowShellViewModel (shellVm)和 MainWindowContentViewModel (contentVm)。 shellVm发布事件,而contentVm订阅该事件。

Shell VM看起来类似于以下内容。我省略了许多细节。

// ctor
public MainWindowShellViewModel(IEventAggregator eventAggregator)
{
    _EventAggregator = eventAggregator ?? throw new ArgumentNullException(nameof(IEventAggregator) + " service injected is null!!!");

    _AppStartingClosingEventToken = _EventAggregator.GetEvent<AppStartingClosingEvent>();
}

private void MainWindowShellLoaded()
{
    var payload = new AppStartingClosingEventData();
    payload.Data = "MainWindowStarting";
    _AppStartingClosingEventToken.Publish(payload);
}

AppStartingClosingEvent是一种毫无疑问的类型,如下所示。

public class AppStartingClosingEvent : PubSubEvent<AppStartingClosingEventData>
{ }

public class AppStartingClosingEventData
{
    public string Data { get; set; }
}

最后,contentVm如下所示。

public MainWindowContentViewModel(IEventAggregator eventAggregator)
{
    _AppClosingEventToken.Subscribe(AppStartingClosing);
}
private void AppStartingClosing(AppStartingClosingEventData appStartingClosingEventData)
{
    if (appStartingClosingEventData.Data == "MainWindowStarting")
        LoadState(appStartingClosingEventData);
    if (appStartingClosingEventData.Data == "MainWindowClosing")
        SaveState(appStartingClosingEventData);
}

我想测试是否使用正确的数据调用contentVm内部的方法 AppStartingClosing 。我正在使用起订量 我的想法不多了。请提出建议。尝试了以下方法,但到目前为止没有成功。

How do I test Prism event aggregator subscriptions, on the UIThread?

Using Moq to verify a Prism event subscription fails

Unit testing with Moq, Prism 6, and Event Aggregation

Moq Event Aggregator Is it possible             // Verifying a delegate was called with Moq

编辑

这是我尝试过的。

// Arrange
var mockingKernel = new MoqMockingKernel();
var eventAggregatorMock = mockingKernel.GetMock<IEventAggregator>();
var eventBeingListenedTo = new AppStartingClosingEvent();
eventAggregatorMock.Setup(e => e.GetEvent<AppStartingClosingEvent>()).Returns(eventBeingListenedTo);            
var vm = mockingKernel.Get<MainWindowContentViewModel>();
var evData = new AppStartingClosingEventData();
evData.Data = "MainWindowStarting";

        // Act
eventBeingListenedTo.Publish(evData);

现在,我该怎么办?我什至不清楚我是否正确采取了措施。

1 个答案:

答案 0 :(得分:1)

  

现在我该怎么办?

eventBeingListenedTo.Publish(evData);之后,看看SaveState到底应该发生什么效果。

  

我什至不清楚我是否正确采取了措施。

您不想测试某个类中的一个方法是否被该类的另一个方法调用。

所以不要尝试做

subjectUnderTest.DoStuff();

MagicallyVerifyThatThisGotCalled( () => subjectUnderTest.SomeEffect() );

你应该做

var subjectUnderTest = new SubjectUnderTest( serviceMock.Object );

subjectUnderTest.DoStuff();

serviceMock.Verify( x => x.SomeEffectOnTheService(), Times.Once );
Assert.That( subjectUnderTest.SomePropertyThatsChanged, Is.EqualTo( newValue ) );

SubjectUnderTest内部为实现所需效果所做的任何事情均不在测试范围之内。 SubjectUnderTest是私有的,只要完全完成,您都不在乎如何。在测试时,请查看被测对象的外部可见状态,以及其对依存关系的作用。

相关问题