How do I make a data file available to unit tests?

后端 未结 2 1883
太阳男子
太阳男子 2021-01-23 05:10

I\'m using VS2008 TFS (with MSTest).

I have a unit test that works reliably, relying on a data file in a subfolder of the project (ie testproject1\\TestData). The data f

相关标签:
2条回答
  • 2021-01-23 05:37

    I know this is late. The accepted answer is technically right. However, over the years I have found that the DeploymentAttribute approach becomes cumbersome when you have too many data files. In my case it was nearing thousand. The problems were

    1. Remember to mark every file as Copy to output .
    2. Every time I would debug the project, the thousand data files would get copied over to MyUnitTestProject\Bin\Debug. This slowed down my overall development and debugging experience.

    Proposed solution

    My proposed solution is let the data files remain as static files in the Unit testing project and simply determine the absolute path using the Location property of the executing System.Reflection.Assembly. This has worked really well for me, considering the large number of data files I was dealing with. Worked well when the tests ran on Jenkins build server.

    You can refer to the code snippet I have posted in another answer. NUnit DeploymentItem

    Drawback with my proposed solution

    You do not get a new deployment folder created every time your tests run. If your unit tests are going to create output files, then you are responsible for generating a new folder under the location of the unit testing assembly, which would be usually MyUnitTestProject\Bin\Debug.

    Posting the code here because my hyperlinked answer was deleted Somebody by the name Martijn Pieters deleted my original answer because he did not like the duplication. Therefore I am reproducing the original code here.

        internal static string GetFullPathToFile(string pathRelativeUnitTestingFile)
    {
        string folderProjectLevel = GetPathToCurrentUnitTestProject();
        string final = System.IO.Path.Combine(folderProjectLevel, pathRelativeUnitTestingFile);
        return final;
    }
    /// <summary>
    /// Get the path to the current unit testing project.
    /// </summary>
    /// <returns></returns>
    private static string GetPathToCurrentUnitTestProject()
    {
        string pathAssembly = System.Reflection.Assembly.GetExecutingAssembly().Location;
        string folderAssembly = System.IO.Path.GetDirectoryName(pathAssembly);
        if (folderAssembly.EndsWith("\\") == false) folderAssembly = folderAssembly + "\\";
        string folderProjectLevel = System.IO.Path.GetFullPath(folderAssembly + "..\\..\\");
        return folderProjectLevel;
    }
    
    0 讨论(0)
  • 2021-01-23 05:42

    Use the DeploymentItem attribute (more info here).

    Edit: As per the OP, the .testrunconfig file must also be edited.

    0 讨论(0)
提交回复
热议问题