canton7 / Stylet

A very lightweight but powerful ViewModel-First MVVM framework for WPF for .NET Framework and .NET Core, inspired by Caliburn.Micro.
MIT License
995 stars 144 forks source link

How to test `RequestClose` method in unit test? #81

Closed wakuflair closed 5 years ago

wakuflair commented 5 years ago

Hi, I'm testing a ViewModel, which will call RequestClose(true) somewhere, the unit test method is like this:

        public void LoginTest()
        {
            var vm = _container.Get<LoginViewModel>();
            vm.UserName = "waku";
            vm.Password = "123";
            vm.Login();

           // Here how can I assert that the ReuqestClose is called and the result value is true?
        }

Now it failed with the exception:

Unable to close ViewModel XXX.LoginViewModel as it must have a conductor as a parent (note that windows and dialogs automatically have such a parent)

I know it's related to WindowConductor, but just can't figure it out.

canton7 commented 5 years ago

You can see that exception raised here. From there, we can tell that this is because either this.Parent isn't set of its value isn't an IChildDelegate.

The Parent property is publically settable (and it's set by a conductor, if there is one).

For your test, create a mock which implements IChildDelegate, set LoginViewModel.Parent = yourModel;, then test that your mock's CloseItem method is called.

wakuflair commented 5 years ago

It works! Thanks @canton7 !