I have a Silverlight testing project using the Silverlight Unit Test Framework.
I want to test a method in my view model which takes FileInfo objects. This seems to work fine when I test it manually through the UI.
Now I want a unit test just for the AddDocument method. I don’t want to test actually clicking the button or simulate clicking a button – I just want to test that the AddDocument method.
Here’s the code behind from the view. The mySessionViewModel object is in the DataContext. The method I want to test is mySessionViewModel.AddDocument();
private void Button_Click_1(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter =
"Text Files (.txt)|*.txt|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = true;
bool? userClickedOK = openFileDialog1.ShowDialog();
if (userClickedOK == true)
{
IList<FileInfo> files = new List<FileInfo>();
foreach (FileInfo file in openFileDialog1.Files)
{
mySessionViewModel.AddDocument(file);
}
}
}
I put some test files in a subdirectory of the web project and tried this, but it throws a SecurityException consistent with Silverlight’s security model:
SessionView sessionViewModel = new SessionViewModel();
DirectoryInfo di = new DirectoryInfo("testFiles");
var files = di.EnumerateFiles();
foreach (var file in files)
{
sessionViewModel.AddDocument(file);
}
// assert some stuff
The main problem here is you want to Unit Test a method that takes a
FileInfoas a parameter. However there is no automated way to create an instance ofFileInfo.Hence to unit test this method you should consider changing the type of the parameter. Its quite likely that the internals of this method only access a handful of the properties and methods on the
FileInfo. Hence create an interface that represents those members and change the method to use the interface rather than theFileInfodirectly.Now you can create a wrapper class for
FileInfothat implements the interface and you can also create another class for use in unit testing that implements the same interface but gets its content elsewhere.