How to get Directory while running unit test

后端 未结 14 818
余生分开走
余生分开走 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:45

    Further to @abhilash's comment.

    This works in my EXE's, DLL's and when tested from a different UnitTest project in both Debug or Release modes:

    var dirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location.Replace("bin\\Debug", string.Empty));
    
    0 讨论(0)
  • 2021-02-02 05:46

    According to https://github.com/nunit/nunit/issues/742#issuecomment-121964506

    For NUnit3 , System.Environment.CurrentDirector is never changed, so it shall be the path of solution.

    Eg:

    string szProjectPath = System.Environment.CurrentDirectory + @"\where\your\project\is";
    

    I prefer fixed location rather than GetParent(). One drawback of GetParent is when build is changed from AnyCPU to x86, default path would be changed from bin\Debug to bin\x86\Debug. Need to get another parent, and it's pain in the neck.

    Also, you may still access to you test assemblies at TestContext.CurrentContext.TestDirectory.

    Edit: Note: There are many changes in NUnit3. I will suggest reading through the documentation about "Breaking changes"

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