Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock DragEventArgs

I am trying to unit test this method that is called from my ViewModel:

  public virtual string[] ExtractFilePaths(DragEventArgs dragEventArgs)
  {
     string[] droppedPaths = null;

     if (dragEventArgs.Data.GetDataPresent(DataFormats.FileDrop))
     {
        droppedPaths = dragEventArgs.Data.GetData(DataFormats.FileDrop, true) as string[];
     }

     return droppedPaths;
  }

I have this method wired up with Caliburn. I know it's a pretty simple method that almost exclusively uses framework classes, but I feel it still needs testing. The problem is, Moq cannot mock the DragEventArgs. Is there a way around this or should I just not bother testing this method?

like image 320
michaelkoss Avatar asked Sep 10 '12 18:09

michaelkoss


2 Answers

Hopefully I am not missing anything with Calibrun, but why mock DragEventArgs when you can create one? The important part is the IDataObject part, which is an interface and can easily be mocked.

[Test]
public void ExtractFilePaths_WithFileDrop_ReturndDropPaths()
{
    var fileList = new[] {@"c:\path\path\file1.txt", @"d:\path2\path2\file2.txt"};
    var stubData = Mock.Of<IDataObject>(x =>
                                        x.GetDataPresent(DataFormats.FileDrop) == true &&
                                        x.GetData(DataFormats.FileDrop, true) == fileList);

    var dragEventArgs = new DragEventArgs(stubData, 0, 0, 0, DragDropEffects.Move, DragDropEffects.Scroll);

    var subject = new Subject();

    // Act
    var result = subject.ExtractFilePaths(dragEventArgs);

    // Assert
    Assert.That(result, Is.Not.Null, "Expected array to be returned");
    Assert.That(result, Is.EquivalentTo(fileList));
}
like image 161
Steven Mortimer Avatar answered Nov 01 '22 05:11

Steven Mortimer


Replace DragEventArgs class with only the data you want to use in your function. DragEventArgs belongs to UI, not ViewModel.

like image 37
Vili Avatar answered Nov 01 '22 05:11

Vili