programing tip

단위 테스트를 실행하는 동안 디렉터리를 가져 오는 방법

itbloger 2020. 11. 14. 09:57
반응형

단위 테스트를 실행하는 동안 디렉터리를 가져 오는 방법


안녕하세요, 단위 테스트를 실행할 때 내 프로젝트가 파일을 검색하기 위해 실행중인 디렉토리를 가져오고 싶습니다.

MyProject라는 테스트 프로젝트가 있다고 가정합니다. 내가 실행하는 테스트 :

AppDomain.CurrentDomain.SetupInformation.ApplicationBase

그리고 나는 "C:\\Source\\MyProject.Test\\bin\\Debug".

이것은 내가 추구하는 것에 가깝습니다. 나는 그 bin\\Debug부분을 원하지 않는다 .

아무도 내가 어떻게 얻을 수 있는지 알아 "C:\\Source\\MyProject.Test\\"?


나는 그것을 다르게 할 것입니다.

해당 파일을 솔루션 / 프로젝트의 일부로 만드는 것이 좋습니다. 그런 다음 마우스 오른쪽 버튼을 클릭-> 속성-> 출력으로 복사 = 항상 복사.

그러면 해당 파일이 출력 디렉토리 (예 : C : \ Source \ MyProject.Test \ bin \ Debug)에 복사됩니다.

편집 : 출력으로 복사 = 최신 옵션이 더 좋은 경우 복사


일반적으로 다음과 같이 솔루션 디렉토리 (또는 솔루션 구조에 따라 프로젝트 디렉토리)를 검색합니다.

string solution_dir = Path.GetDirectoryName( Path.GetDirectoryName(
    TestContext.CurrentContext.TestDirectory ) );

그러면 테스트 프로젝트에서 만든 "TestResults"폴더의 상위 디렉터리가 제공됩니다.


Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;

필요한 디렉토리를 제공합니다 ....

같이

AppDomain.CurrentDomain.SetupInformation.ApplicationBase 

아무것도주지 않는다

Directory.GetCurrentDirectory().

이 링크를보세요

http://msdn.microsoft.com/en-us/library/system.appdomain.currentdomain.aspx


@abhilash의 의견에 더.

이것은 내 EXE, DLL 디버그 또는 릴리스 모드에서 다른 UnitTest 프로젝트 에서 테스트 할 때 작동 합니다.

var dirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location.Replace("bin\\Debug", string.Empty));

/// <summary>
/// Testing various directory sources in a Unit Test project
/// </summary>
/// <remarks>
/// I want to mimic the web app's App_Data folder in a Unit Test project:
/// A) Using Copy to Output Directory on each data file
/// D) Without having to set Copy to Output Directory on each data file
/// </remarks>
[TestMethod]
public void UT_PathsExist()
{
    // Gets bin\Release or bin\Debug depending on mode
    string baseA = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
    Console.WriteLine(string.Format("Dir A:{0}", baseA));
    Assert.IsTrue(System.IO.Directory.Exists(baseA));

    // Gets bin\Release or bin\Debug depending on mode
    string baseB = AppDomain.CurrentDomain.BaseDirectory;
    Console.WriteLine(string.Format("Dir B:{0}", baseB));
    Assert.IsTrue(System.IO.Directory.Exists(baseB));

    // Returns empty string (or exception if you use .ToString()
    string baseC = (string)AppDomain.CurrentDomain.GetData("DataDirectory");
    Console.WriteLine(string.Format("Dir C:{0}", baseC));
    Assert.IsFalse(System.IO.Directory.Exists(baseC));


    // Move up two levels
    string baseD = System.IO.Directory.GetParent(baseA).Parent.FullName;
    Console.WriteLine(string.Format("Dir D:{0}", baseD));
    Assert.IsTrue(System.IO.Directory.Exists(baseD));


    // You need to set the Copy to Output Directory on each data file
    var appPathA = System.IO.Path.Combine(baseA, "App_Data");
    Console.WriteLine(string.Format("Dir A/App_Data:{0}", appPathA));
    // C:/solution/UnitTestProject/bin/Debug/App_Data
    Assert.IsTrue(System.IO.Directory.Exists(appPathA));

    // You can work with data files in the project directory's App_Data folder (or any other test data folder) 
    var appPathD = System.IO.Path.Combine(baseD, "App_Data");
    Console.WriteLine(string.Format("Dir D/App_Data:{0}", appPathD));
    // C:/solution/UnitTestProject/App_Data
    Assert.IsTrue(System.IO.Directory.Exists(appPathD));
}

나는 일반적으로 그렇게하고 "..\..\"원하는 디렉토리에 도달하기 위해 경로에 추가 합니다.

그래서 당신이 할 수있는 것은 다음과 같습니다.

var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"..\..\";

NUnit의 경우 이것이 내가하는 일입니다.

// 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;

필요한 경우 거기에서 필요한 경우 다른 디렉토리로 다시 이동할 수 있습니다.

dir = Path.Combine(dir, "MySubDir");

이것이 도움이되는지 확실하지 않지만 다음 질문에서 간략하게 다룰 것 같습니다.

Visual Studio 솔루션 경로 환경 변수


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.


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;

My approach relies on getting the location of the unit testing assembly and then traversing upwards. In the following snippet the variable folderProjectLevel will give you the path to the Unit test project.

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 + "..\\..\\");

You can do it like this:

using System.IO;

Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, @"..\..\"));

참고URL : https://stackoverflow.com/questions/10204091/how-to-get-directory-while-running-unit-test

반응형