How to get Directory while running unit test

后端 未结 14 834
余生分开走
余生分开走 2021-02-02 05:07

Hi when running my unit test I\'m wanting to get the directory my project is running in to retrieve a file.

Say I have a Test project named MyProject. Test I run:

<
相关标签:
14条回答
  • 2021-02-02 05:38

    For NUnit this is what I do:

    // Get the executing directory of the tests 
    string dir = NUnit.Framework.TestContext.CurrentContext.TestDirectory;
    
    // Infer the project directory from there...2 levels up (depending on project type - for asp.net omit the latter Parent for a single level up)
    dir = System.IO.Directory.GetParent(dir).Parent.FullName;
    

    If required you can from there navigate back down to other directories if required:

    dir = Path.Combine(dir, "MySubDir");
    
    0 讨论(0)
  • 2021-02-02 05:41

    I normally do it like that, and then I just add "..\..\" to the path to get up to the directory I want.

    So what you could do is this:

    var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"..\..\";
    
    0 讨论(0)
  • 2021-02-02 05:42

    You can do it like this:

    using System.IO;
    
    Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, @"..\..\"));
    
    0 讨论(0)
  • 2021-02-02 05:43

    I would do it differently.

    I suggest making that file part of the solution/project. Then right-click -> Properties -> Copy To Output = Copy Always.

    That file will then be copied to whatever your output directory is (e.g. C:\Source\MyProject.Test\bin\Debug).

    Edit: Copy To Output = Copy if Newer is the better option

    0 讨论(0)
  • 2021-02-02 05:44

    The best solution I found was to put the file as an embedded resource on the test project and get it from my unit test. With this solution I don´t need to care about file paths.

    0 讨论(0)
  • 2021-02-02 05:44

    In general you may use this, regardless if running a test or console app or web app:

    // returns the absolute path of assembly, file://C:/.../MyAssembly.dll
    var codeBase = Assembly.GetExecutingAssembly().CodeBase;    
    // returns the absolute path of assembly, i.e: C:\...\MyAssembly.dll
    var location = Assembly.GetExecutingAssembly().Location;
    

    If you are running NUnit, then:

    // return the absolute path of directory, i.e. C:\...\
    var testDirectory = TestContext.CurrentContext.TestDirectory;
    
    0 讨论(0)
提交回复
热议问题