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

3
我有一个视图模型,其中包含算法列表。该列表在 View 中显示为 ListBox,并且用户可以选择其中一个算法。选择算法后,用户可以单击按钮,执行视图模型中的命令,加载所选算法的详细信息的不同视图。
我想通过创建单元测试来测试这个功能,并确保导航也可以正常工作。但我猜想需要对区域管理器进行一些额外的初始化,因为 IRegionManager.Regions 集合为 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


https://dev59.com/9UjSa4cB1Zd3GeqPGpQZ - StepUp
1个回答

0

我曾经遇到同样的问题一段时间,然后我模拟了所有需要的区域管理器。如果这对你有帮助,请参考下面的代码片段。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接