wpfmvvmprismmouseevent

Unit testing functions relying on MouseEventArgs?


I am currently working on a project of mine which is a MSPaint-like WPF application. However I don't paint with pencil tools or something similar but with objects (Rectangle, Circle, Triangle etc.). I use Prism and the MVVM model to achieve testability and maintainability.

I've now run into a problem. I have a CanvasView.xaml that's (as the name suggests) the canvas I am painting on. I have implemented custom Prism CommandBehaviors (ie. MouseDownCommandBehavior) to provide a way to bind the commands of the ViewModel to the mouse actions on the canvas.

The basic setup looks like this:

public DelegateCommand<MouseEventArgs> MouseLeftButtonDownCommand { get; set; }

public CanvasViewModel(ICanvasView view, IEventAggregator eventAggregator) : base(view)
{
    m_View = view;
    m_EventAggregator = eventAggregator;
    m_EventAggregator.GetEvent<ToolboxSelectionChangedEvent>().Subscribe(OnToolboxSelectionChanged);


    MouseLeftButtonDownCommand = new DelegateCommand<MouseEventArgs>(OnMouseLeftButtonDown);
}

public void OnMouseLeftButtonDown(MouseEventArgs args)
{
    Point position = m_View.GetPosition(args);

    if(SelectedObject!=null){
        PaintObject po = SelectedObject.Clone();
        Canvas.SetLeft(po,position.X);
        Canvas.SetTop(po,position.Y);
        PaintObjects.Add(po);
    }
}

Some things not present in the code:

The question is how can I unit test the OnMouseLeftButtonDown method? The problem is that it heavily relies on MouseEventArgs and I don't really know a good way to mock/stub MouseEventArgs.


Solution

  • Use an additional layer to consume and emit mouse events. Then you can stub/mock out that layer for your unit tests.