如何使用单元测试和 Prism 6 (WPF 和 MVVM) 测试区域管理器导航



我有一个包含算法列表的视图模型。该列表在视图中显示为ListBox,用户可以选择其中一种算法。选择算法后,用户可以点击一个按钮,该按钮应该在视图模型中执行一个命令,该命令加载不同的视图,并包含所选算法的详细信息。

我想通过创建一个单元测试来测试这一点,并确保导航也能正常工作。但我想我需要为区域管理器做一些额外的初始化,因为IRegionManager.Regies集合为null,并且由于它是只读的,我无法创建它。

[TestClass]
public class MockingAlgorithmsTests
{
    [TestMethod]
    public void AlgorithmVM_LoadSelectedAlgorithmCommand()
    {
        Mock<IRegionManager> regionManagerMock = new Mock<IRegionManager>();
        Mock<IEventAggregator> eventAgregatorMock = new Mock<IEventAggregator>();
        IAlgorithmService algorithmService = new MockingAlgorithmService();
        AlgorithmsViewModel algorithmsVM = new AlgorithmsViewModel(regionManagerMock.Object, eventAgregatorMock.Object, algorithmService);
        // select algorithm
        algorithmsVM.SelectedAlgorithm = algorithmsVM.Algorithms.First();
        // execute command which uses the previous selected algorithm
        // and navigates to a different view
        algorithmsVM.LoadSelectedAlgorithmCommand.Execute(null);
        // check that the navigation worked and the new view is the one 
        // which shows the selected algorithm
        var enumeratorMainRegion = regionManagerMock.Object.Regions["MainContentRegion"].ActiveViews.GetEnumerator();
        enumeratorMainRegion.MoveNext();
        var viewFullName = enumeratorMainRegion.Current.ToString();
        Assert.AreEqual(viewFullName, "TestApp.AlgorithmViews.AlgorithmDetails");
    }
}

这就是测试,任何建议都会有帮助。谢谢你,Nadia

我有一段时间面临同样的问题,然后我嘲笑了区域经理所需要的一切。如果这对您有帮助,请参阅下面的代码片段。

var regionManager = new Mock<IRegionManager>();     
var navigationJournal = new Mock<IRegionNavigationJournal>();
                navigationJournal.Setup(x => x.GoBack()).Callback(() =>
                {
                   // Verify back operation performed
                });
    
var regionNavigationService = new Mock<IRegionNavigationService>();
                regionNavigationService.Setup(x => x.Journal).Returns(navigationJournal.Object);
    
var navRegionMock = new Mock<IRegion>();
                navRegionMock.Setup(x => x.NavigationService).Returns(regionNavigationService.Object);
                regionManager.SetupGet(x => x.Regions[RegionNames.ShellContentRegion]).Returns(navRegionMock.Object);

最新更新