简体   繁体   English

WPF MVVM - 单元测试命令 - 私有vs公共方法?

[英]WPF MVVM - Unit Testing a command - Private vs Public methods?

基本上,如果我使用MVVM并公开公共ICommands,我的代表应该公开还是私有?

我会将它们设为私有 - 它们不属于您的类的公共接口 ,这就是公共ICommand属性的用途。

Personally, I'd go with private methods and I'll tell you why. 就个人而言,我会采用私人方法,我会告诉你原因。 You're exposing an ICommand , which to me says that the consuming view should call a CanExecute prior to calling an Execute. 你正在暴露一个ICommand ,对我来说,消费视图应该在调用Execute之前调用CanExecute。 If they don't, they're going against the API and shooting themselves in the foot and at that point it is out of your hands. 如果他们不这样做,他们就会违反API并在脚下射击自己,那时它就不在你的手中了。 Just like if someone used reflection to set an important private variable to null and broke your class design because of this... shooting themselves in the foot. 就像有人使用反射将一个重要的私有变量设置为null并因此而破坏了你的类设计......在脚下射击自己。 So why make the members private? 为什么要让会员私密? Because there is no need to expose members that should not be called directly. 因为不需要公开不应该直接调用的成员。


Basically, when you unit test the members you don't do so individually, you do so in the way the API intends for the members to be executed. 基本上,当您单独测试成员时,不是单独执行,而是按照API打算执行成员的方式进行。 So, you're not really testing the members, but moreover you're testing the command, which again means they should be tested in a pair in the specific order of: 所以,你并没有真正测试成员,而且你正在测试命令,这也意味着他们应该按照以下特定顺序进行成对测试:

if (CanExecute)
{
    Execute;
}

I have MVVM for something simple control of increase, decrease buttons and Slider show value. 我有MVVM用于简单控制增加,减少按钮和滑块显示值。

If you have test ICommand and INotifyPropertyChanged, you can make kind of UnitTest: 如果你有测试ICommand和INotifyPropertyChanged,你可以做一些UnitTest:

[TestMethod]
public void TestViewModel3()
{
    int min = -10;
    int max = 10000;
    int initVal = 50;
    bool initState = false;

    ToglledSliderModel model = new ToglledSliderModel(initState, initVal, min, max);
    ToglledSliderViewModel viewModel = new ToglledSliderViewModel();
    viewModel.Model = model;

    int status = 567;
    viewModel.PropertyChanged += delegate
    {
        status = 234;
    };

    for (int i = 1; i < 100; i++)
    {
        status = 567;
        ICommand ic = viewModel.IncreaseValue;
        ic.Execute(this);
        Thread.Sleep(2);
        Assert.AreEqual(status, 234);
        Assert.AreEqual(model.SliderValue, initVal + i);
    }
}

you can see, i test INotifyPropertyChanged behaviour and ICommand executing 你可以看到,我测试INotifyPropertyChanged行为和ICommand执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM