Search code examples
wpfunit-testingmodal-dialogrhino-mocks

Rhino Mock and WPF Window Dialog


I'm writing Unit-Tests for an OK_Execute Command in an MvvM-Scenario.

Now that's working fine until the method calls:

        obj.DialogResult = !datumExistiertBereits || datumUeberschreiben;
        obj.Close();  

where the first line fires the following InvalidOperationException:

DialogResult can be set only after Window is created and shown as dialog.

Now I wonder how I can make my window stub object responsible to these calls without really showing the dialog in my Unit-Tests?

Thanks in advance

Steav


Solution

  • You need to move the responsability to show an actual dialog (or any window for that matter) to a seperate class, which implements an interface, and only hand an instance of that class to the VM using it.

    Example:

    interface IDialogService
    {
      Result ShowDialog();
    }
    
    class ViewModel
    {
      ViewModel( IDialogService dlgService ) { ... }
    
      void ExecuteSomeCommand()
      {
        var result = dlgService.ShowDialog(); 
      }
    }
    
    //actual code
    class ActualDialog : IDialogService { ... }
    
    var vm = new ViewModel( new ActualDialog() );
    
    //test pseudocode (sorry I don't know RhinoMock)
    var vm = new ViewModel( RhinoMock.GetMeAMockFor<IDialogService>() );
    

    You can easily see the advantages this has: vm doesn't know anything at all about the dialog and does not depend on code for showing/closing windows anymore, plus you can test the code by mocking the dialog service.