When you build automated WPF functional test using White in which you need to open a file through a Windows open file dialog, you will be confronted with the following issue. Windows open file dialog remember the last path with which you opened a file.

So you might have some unit tests that are green for a while which starts to be red for no apparent reasons.

The solution I came to is as this.

First I use Visual Studio, Copy to Output Directory, to copy the needed file to the output directoy in which your software will be started by the unit tests, e.g. for notValidVersionZip.zip

So now I am sure that the needed file is in the same path than the application. I then also need to be sure that when the application start the Windows open file dialog it points to this path. In the past implementation I was just using a filename and was lucky enough the path used by the Windows open file dialog was the correct one.

To get to the correct path is easy. We just navigate to the correct path using the Windows open file dialog in an automated way. The correct path is the path in which the application as been started, so you can get it like that:

  1. /// <summary>
  2. /// Gets the current path.
  3. /// </summary>
  4. /// <returns></returns>
  5. private static string GetCurrentPath()
  6. {
  7.     return Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
  8. }

We have the correct path and we still need to automate the Windows open file dialog to navigate to that path. We can do this like that:

  1. protected void Open(string filename)
  2. {
  3.     OpenButton.Click();
  5.     var openModalWindow =
  6.         MainWindow.ModalWindow(“Please choose a Zip file”, InitializeOption.NoCache);
  7.     Assert.IsNotNull(openModalWindow);
  9.     var splittedPath = GetCurrentPath().Split(new[] { ‘\‘ });
  11.     foreach (var pathPart in splittedPath)
  12.     {
  13.         openModalWindow.Enter(pathPart);
  14.         openModalWindow.Keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.RETURN);
  15.         openModalWindow.WaitWhileBusy();
  16.     }
  18.     openModalWindow.Enter(filename);
  19.     openModalWindow.Keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.RETURN);
  20. }

Basically we split the path into it different path parts that White will enter into the dialog followed by a enter. Don’t forget to use the method WaitWhileBusy() after each enter, otherwise it will be too fast and sometime your test will not go to the correct path and then will not find the file.

Finally White enter the filename followed by enter and the file is opened.


If you are using like me ReSharper to run your unit tests don’t forget to set it up to run tests from Project output folder.